This project contains a demo of how we can use React.createContext()
and useContext()
to provide global state. It differs from the previous example in that this time, the value of the context is being modified in one sibling component, while being read in another.
-
In auth-context.js, we're creating the Context object itself -
AuthContext
. We're importing it whenever we need it. -
In App.jsx, we're establishing an
<AuthContext.Provider>
, which will make itsvalue
available to all descendants. In this case, the value is auser
(which will either beundefined
(when not authenticated), or an object with ausername
property (when authenticated)), along with asetUser()
function which can be used to update theuser
value. -
In UserInfoPage.jsx, we're accessing the value stored in
AuthContext.Provider
, by using theuseContext()
hook. This value will include the user that was added inApp.js
, if any. -
In LoginPage.jsx, we also access the value stored in
AuthContext.Provider
. In this case, we're making use of thesetUser()
function supplied here. Calling this function will cause theuser
state inApp.js
to be changed, which will in turn causeAuthContext.Provider
and all its children to be re-rendered, due to the changed context value.