Context API
Examples
Basic Example
Simple example using Context API to pass a value down to a <Context.Consumer>
. Context requires using a component's state to keep track of the context value when you want to change the context (like toggling a sidebar or changing the current user). You change the context value by updating the component's state, which is reflected in the <Context.Provider>
, and passes it down to any child elements.
Usually you wrap this logic up in a separate component that handles the state and wrapping with provider.
Note that in this case, since we're wrapping the root of the app, it will refresh completely when the context is changed since the state is kept so high up in the tree.
Reducer / Redux-like
Uses a reducer to handle actions dispatched through Context API. Similar to Redux architecture.
In this example, we create a theme switcher with pre-determined options (light or dark).
themeContext.js
:
themeProvider.js
: