I have just finished working on another project, and one of the project requirements was to persist the user's state in the front
end with useContext
. So, I had to relearn how to use useContext
. I wanted to share some of the things I learned.
Typically our state is stored in a component where all the components that need access to it can easily get access to it. In this project, since most of my components needed access to the user, I made a userContext
. To start, you need a file to store your context in. I created a context
folder in my src
folder, and a user.js
file in the context
folder. Then, create the context and the context provider.
Create the context
const UserContext = React.createContext();
Create a provider component
function UserProvider({ children }) {
return <UserContext.Provider value={{ user, setUser }}>{children}</UserContext.Provider>;
}
The value is the context that I am passing, and it will be available to the children of the provider. Now that it's created it needs to be passed in to the application. To do this, I import the UserProvider
into the app and wrap the components in UserProvider
. I also no longer need to pass the user
and setUser
props into the component.
...
import { UserProvider } from "../context/user";
function App() {
return(
<UserProvider>
<AComponent />
</UserProvider>
)
}
...
Now, I need to add the context to the component I'm going to use it in.
import React, { useContext } from "react";
import { UserContext } from "../context/user";
function AComponent() {
const { user, setUser } = useContext(UserContext);
{now you have access to your context values here}
return (
{and here too}
)
}
And, that is how you use context to store state globally. One thing that gave me a lot of trouble was, when I was initializing my user state I initialized it with an empty array rather than null. While I probaly could have rewritten the code to make the first way work, it was giving me a lot of trouble, and changing it to null really helped me out.
Not like this,
const [user, setUser] = useState([])
but like this.
const [user, set user] = useState(null)
Top comments (0)