How to use Context and useReducer for state management in React app? Example Tutorial

Introduction
A React component is made up of props and state. The state can be local or global. Usually, the local state is handled within the component using the setState method in class components and hooks in the functional components. But as the application grows, the state is usually required to be shared among multiple components. The global state is managed using third-party libraries such as Redux

Redux works perfectly but setting up redux is complicated and working with it is more complicated. So for moderate global state management, we can use Context API or the useReducer hook. But, there is one more way for managing the global state and that is by using the Context API and useReducer together.


What are Context and useReducer?

The context in React is a way of sharing data between nested components without having it pass as props. It is used to avoid prop drilling. in simple words, using context, the data can be accessed in the component, doesn’t matter how deeply nested.

The useReducer hook is used to manage complex states in a functional component. It is used as an alternative for useState. The useReducer hook declares a state variable along with a dispatch function. For it, we have to pass the initial state and a reducer to the userReducer hook.

Both of these can be used together for global state management.



Global state management using Context and

We will create a basic React app with multiple components sharing state. Following is the architecture of this app.

  • “App” component has three child components - “Component1”, “Component2”, and “Component3”.
  • “Component1” has two child components - “Increment” and “Decrement”.
  • “Component2” has one child component - “Display”.
  • “Component3” has one child component - “Reset”.

The state will have a “value” whose initial value is 0. The “Increment”, “Decrement”, and “Reset” components will have one button each for updating the state while the “Display” component will display the state on the UI. 

Thus, the state, “value”, is being shared among all the components.

 
How to use Context and useReducer for state management in React app? Example Tutorial




Let’s start by creating a separate file for context, i.e. “context.js”.

import React from "react";

const CounterContext = React.createContext();

export default CounterContext;


Then, we have to create a reducer because the useReducer needs one. Create a new file and name it “reducer.js”. Add the following code to it.
 

const reducer = (state, action) => {

  

  switch (action) {

    case "INCREMENT":

      return {

        value: state.value + 1,

      };

    case "DECREMENT":

      return {

        value: state.value - 1,

      };

    case "RESET":

      return {

        value: 0,

      };

  }

};

 

export default reducer;



To share the state among every component, we have to wrap the “App” component in the context provider. But first, we have to create the state variable and dispatch function using the useReducer hook.

const intialState = {

  value: 0,

};

 

const [value, dispatch] = useReducer(reducer, intialState);



Now, we can wrap the provider with the “value” and “dispatch” around the “App” component.
 

return (

  <CounterContext.Provider

    value={{ counterValue: value, counterDispatch: dispatch }}

  >

    <div className="App">

      <Component1 />

      <Component2 />

      <Component3 />

    </div>

  </CounterContext.Provider>

);



We can use “value” as “counterValue” and “dispatch” as “counterDispatch” in any of the nested components.
 


Increment.js


import React, { useContext } from "react";

import CounterContext from "../context";

 

const Increment = () => {

  const context = useContext(CounterContext);

  return (

    <div>

      <button onClick={() => context.counterDispatch("INCREMENT")}>

        Increment

      </button>

    </div>

  );

};

 

export default Increment;

 


Decrement.js


import React, { useContext } from "react";

import CounterContext from "../context";

 

const Decrement = () => {

  const context = useContext(CounterContext);

  return (

    <div>

      <button onClick={() => context.counterDispatch("DECREMENT")}>

        Decrement

      </button>

    </div>

  );

};

 

export default Decrement;

 


Reset.js


import React, { useContext } from "react";

import CounterContext from "../context";

 

const Reset = () => {

  const context = useContext(CounterContext);

  return (

    <div>

      <button onClick={() => context.counterDispatch("RESET")}>Reset</button>

    </div>

  );

};

 

export default Reset;



Display.js


import React, { useContext } from "react";

import CounterContext from "../context";

 

const Display = () => {

  const context = useContext(CounterContext);

  console.log(context);

  return (

    <div>

      <h1>{context.counterValue.value}</h1>

    </div>

  );

};

 

export default Display;

 




Let’s check if the buttons are successfully updating the state or not.


How to use Context and useReducer for state management?




Yes, everything is working fine. We did not use redux here but still, the state is being managed globally. This is because the context is enabling us to share data among the components while the useReducer hook lets us update it easily.


Wrapping it up
Managing state is one of the most important parts of React application development. It could be done using several ways such as using useState, setState, redux, or mobx. But using Context and useReducer is a very easy and efficient way for managing state globally. In this article, we learned how to update the state using the context and useReducer.

Other React and Web development Articles and resources you may like


Thanks for reading this article so far.  If you like this React and Redux hooks tutorial and examples of useEfect hooks, then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a comment.

P. S. - If you are a beginner and want to learn React.js from scratch and looking for free React courses to learn concepts like components, virtual DOM, etc then I also recommend you to join these free online REact.js courses for beginners. It contains free courses from Udmey, Coursera, edX to learn to React online for FREE.        

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.