-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Designing React Hooks the Right Way
By :
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.
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:
Figure 7.7 – A theme made with light and dark options
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".
Any component that requires the theme can read the settings from ThemeContext. Let's build a theme-aware Button component:
const Button = () => {
...
Change the font size
Change margin width
Change background colour