Implementing themes via context
React Context is used to share values across a tree of React components. Usually, we want to share global values, such as the username
state, the theme of our app, or the chosen language (if the app supports multiple languages).
React Context consists of three parts:
- The context itself, which defines a default value and allows us to provide and consume values
- The provider, which provides (sets) the value
- The consumer, which consumes (uses) the value
Defining the context
First, we have to define the context. The way this works has not changed since Hooks were introduced. We simply use the createContext(defaultValue)
function from React to create a new context object. In this case, we will set the default value to { primaryColor: 'maroon' }
, so our default primary color, when no provider is defined, will be maroon.
Now, let’s get started defining the context:
- Copy the
Chapter04_2
...