DEV Community

Rana Wael
Rana Wael

Posted on

2

React useContext()

Is a way to manage state globally. It is used with the useState Hook to share state between deeply nested components more easily than with useState alone (prop drilling). We can create different types of context that like different stores

const UserContext = createContext() // use UserContext as Provider to wrap the tree of components that need the state Context
function Component1() { 
  const [user, setUser] = useState("Rana"); 
  return (
    <UserContext.Provider value={user}>
    <Component2 user={user}/> 
    </UserContext.Provider>
  ); 
}
//Then in any child component call this context to access its values 
const user = useContext(UserContext)

Enter fullscreen mode Exit fullscreen mode

Note:

  • Provider: provides the information
  • Consumers: receive the information

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series