useContext examples
Context is used for sharing site-wise information, but it can be also very effective in sharing things in a narrower area. In this section, we'll see examples of both cases.
Theme context
One nice and common usage involving a context is theming, which allows the user to switch between a light and dark theme based on their preference. See Figure 7.7:
To implement this feature, let's start with ThemeContext
:
const ThemeContext = React.createContext({ mode: 'light', // or 'dark' })
We can set the default theme with an object supporting a mode
property, which is a string to hold either "light" or "dark".
Design theme context
Any component that requires the theme can read the settings from ThemeContext
. Let's build a theme-aware Button
component:
const Button = () => { ...