This project contains a demo of how we can use React.createContext()
and useContext()
to provide global state.
-
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). -
In UserInfoPage.jsx, we're accessing the value stored in
AuthContext.Provider
, by using theuseContext()
hook. This value will be the user that was added inApp.jsx
, if any. -
Back in
App.jsx
, when we modify theuser
state, the updated user will cause theProvider
, and thus its descendents, to re-render. Upon re-rendering,UserInfoPage
will obtain the updateduser
viauseContext()
to display the appropriate message.