DEV Community

Rana Wael
Rana Wael

Posted on

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)