React Context API and useReducer
To organize the global state on your own, you can use tools that already exist in the React ecosystem, namely the Context API and useReducer
. They represent a powerful duo for managing state, especially in situations where using third-party state managers seems excessive. These tools are ideal for creating and managing global states in more compact applications.
The React Context API is designed to pass data through the component tree without the need to pass props at every level. This simplifies access to data in deeply nested components and reduces prop drilling (passing props through many levels), as illustrated in Figure 12.4. The React Context API is particularly useful for data such as theme settings, language preferences, or user information.
Here’s an example of how to store theme settings using context:
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const theme = 'dark';
...