Creating a custom User Hook
In Chapter 5, Implementing React Contexts, we defined a UserContext
to store the username of the currently logged in user. In Chapter 10, Using Community Hooks, we replaced the UserContext
with a Local Storage Hook. As you may remember, refactoring from the Context Hook to a Local Storage Hook required us to adjust the code in many components.
To avoid such issues in the future, we can put all user related information and functions into a User Hook, which then exposes them to be used by other components.
Creating the custom User Hook
Let’s start by extracting all of our existing code related to dealing with the username into a custom User Hook:
- Copy the
Chapter12_1
folder to a newChapter12_2
folder by executing the following command:$ cp -R Chapter12_1 Chapter12_2
- Open the new
Chapter12_2
folder in VS Code. - Create a new
src/hooks/user.js
file. - Inside it, import the
useLocalStorage
function...