Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 modeExit 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 🧑‍💻

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hi,My name is Collins Mutai. I'm a Web Developer based in Nairobi, Kenya. I like UI/UX, Web Design, WordPress Development, and Full Stack Web Development.
  • Location
    Nairobi, Kenya
  • Work
    Web Developer
  • Joined

More fromCollins Mutai

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp