DEV Community

Cover image for React useContext to Manage State
Collins Mutai
Collins Mutai

Posted on

React useContext to Manage State

I struggled with useContext before I could wrap my head around it. It turns out it's really a simple and elegant way to persist data in a react application.
To create a context we need to import from react.
import {useContext} from 'react';
Then create an instance of the context.
export const UserContext = useContext.create({})
Then create a wrapper and export it because we'll need to wrap the context around all our components.

const [name, setName]=(null)
export function ContextProvider({children}){
return (
<UserContext.Provider value={name,setName}>
{children}</UserContext.Provider>
)
}

This makes it possible to provide for any of our routes, the value inside our context. So wrapping the ContextProvider in top level component is key. We can do so in the root file. <ContextProvider><App/></ContextProvider>
We can also wrap the context around our routes. <ContextProvider><Routes><Route path={'/'} element={<Home/>}/></Routes></ContextProvider>
For instance when a user logs in we can set the name of the user inside the context therefore making it accessible from any component that might require it.

import {useContext,useState} from react';
const {UserContext} = './UserContext'
const [username, setUsername] = useState('')
const {setName} = useContext(UserContext);
setName(username)

Let say inside our header component we need to find out the name of the currently logged user. We can do so by tapping into the context and reading the name that's currently stored.

import {useContext,useState} from react';
const {UserContext} = './UserContext'
const Header = ()=> {
const {name} = useContext(UserContext)

return (
<>
{name && (
<p></p>
)}

</>
)
}
Enter fullscreen mode Exit fullscreen mode

As you can see the useContext hook is really powerful and comes handy in small to medium size applications where you don't need redux or other state management tools to manage complex state. Thanks all for checking this out. Happy coding 🧑‍💻

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more