How to Managing User data better with React Hooks & Context
3 min read
For every frontend developer, managing user data is one of the most primal tasks. When React introducing the Hooks API in their latest release, I started experimenting with it and figured out some of the ways it can where it can help make the code cleaner without compromising on the functionality.
Getting familiar with React Context API
React Context API works as a portal when you need to pass down the state of some component to a child which is 3 or more level down. This cringy feeling of passing down props recursively is known as “props-drilling”. The bigger the codebase, the more complicated and uglier it gets.
What is React Hooks exactly?
React Hooks is like providing your simple React function some stateful superpowers. There is a list of hooks you can read about in this helpful article by Stan Starr. By the end of the post, you would have used all the three hooks.
Enough theory, Come to the code already
Creating a React Context
To keep the project structure cleaner, I like to declare the contexts in their separate files.
Here is a react context named UserContext with an empty object as default value
Linking the Context to a State
Linking the context to a React function called
UserDataManager and make it stateful using the
useState API. Now you are passing the state variable,
userData and the functions to manipulate that value appropriately i.e.
logoutUser to the
Provider so that it will be accessible anywhere deeper in this react tree node using Context Consumer.
Implement cache to persist state
Implemented localStorage to persist the user data
We would want the web app to remember user data when the user comes back, to do that we need to save that data to
localStorage is getting checked for a valid value of user data and if there is one, it gets injected as the default value of
For updating the value in
localStorage, we use
useEffect which listens to any change happening in the
userData and will update or invalidate the cache accordingly.
Consuming the User Data
Till now, we have worked on storing the user data and created functions to manipulate it. Now its time to attach it to some UI.
Wrapping the root App Component with the Manager
First, we need to wrap the root
AppComponent with the Manager we just made.
And lastly, we have finally reached the third and last hook of the tutorial,
useContext. This hook helps to keep the ContextConsumer code cleaner.
It takes the whole
Context as a parameter and returns the whole content of that context without
After linking the data to the
UserCardComponent, You are done with a way slimmer and cleaner Context Management System that is accessible everywhere inside your code. 🎉 🎉 🎉
and that is all for now. Feel free to comment below if you have any doubts or queries.