
This allows us to import it into the component where we want to consume this context. We need to export this object from this file. The next step is to create a Context object for the theme. In the src folder, create a new file called ThemeContext.js.
#React usecontext free
Take a look at them or feel free to edit them in src/App.css. I’ve also written all the CSS styles required for the dark mode and the light mode. In the starter code, I’ve set up a simple screen with text and a button to switch to dark mode. If you’d like to take a look at the final code, please refer to this GitHub Repository. Follow the Repository’s README for instructions. This is what the process involves: Create a context object by using React.

You can clone it from this repository on GitHub. useContext () can prove to be a simple alternative to other state management libraries if your data is not complicated and the application is small. To focus more on the use of the context API and reducers, I’ve prepared a starter code.
#React usecontext update
If you pass this state and dispatch to the value prop of the Context Provider, you can consume the state and update it using the dispatch from any consumer. Based on the type of action, the function will return a new state.Ĭonst = useReducer( reducer, initialState) ReducersĪ Reducer is a function that takes 2 arguments, the current state, and an action. This is because whenever the context’s value changes, the descendant components of the Provider will be re-rendered. You should, therefore, only use it for low-frequency updates like the theme and authentication. However, the Context API is not built for high-frequency updates at the time of writing this article. Furthermore, it results in a smaller bundle size and improved project maintainability. If you want to learn more about Redux, check out this tutorial.Ĭontext API is a perfect alternative to Redux when building small applications. Since Redux is an external library, it is supported by other frameworks such as Angular, Flutter, etc.

It has rules ensuring that the state can only be updated in a predictable manner. Redux serves as a centralized store for the state that needs to be used across your entire application. When to use the Context API instead of Redux We need to create a Context object using the createContext method. The context API consists of three building blocks:
#React usecontext how to
How to manage state that is required in multiple components (not necessarily a direct child component) without passing it all the way down.

In other words, React’s Context API is there to solve a simple problem.
