Managing Global State Using UseContext And UseReducer Hook In React

React is a popular JavaScript library used for building user interfaces. It provides a component-based architecture and state management system to build complex applications.

In this blog, we will discuss a code snippet that demonstrates the use of React Context API, useReducer hook for global state management in a React application

In this blog post, we’ll explore how to use React’s  useContext  and useReducer hooks.

Let’s Start:

In `src` folder of your app you can create a contexts folder with a new file named UserContext.js

To begin, we will define an initial state object that represents the data. The initialState object includes an empty array for data.

import React, { createContext, useContext, useReducer } from 'react';

const initialState = {
    users: [],
};

Next, we define a reducer function that handles different types of actions to update the state. These actions include adding a new user, updating an existing user, and deleting a user.

const userReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_USER':
      return {
        ...state,
        users: [...state.users, action.payload],
      };
    case 'UPDATE_USER':
      const updatedCUsers = state.users.map(user =>
        user.id === action.payload.id ? action.payload : user,
      );
      return {
        ...state,
        users: updatedCUsers,
      };
    case 'DELETE_USER':
      const filteredUsers = state.users.filter(
        user => user.id !== action.payload,
      );
      return {
        ...state,
        users: filteredUsers,
      };
  
    default:
      return state;
  }
};
Creating The User Context

To manage the users throughout the application, we create a UserContext using React’s createContext function. The context object includes properties for adding users and accessing the stored users.

export const UserContext = createContext({
  addUser: arg => {},
  users: [],
  });
  
export const useUser = () => useContext(UserContext);

We can export a custom hook useUser that will be used by the components to consume the users’ global state.

Creating The UserProvider Component
export const UserProvider = ({ children }) => {
  const [state, dispatch] = useReducer(userReducer, initialState);
  return (
    <UserContext.Provider value={[state, dispatch]}>
      {props.children}
    </UserContext.Provider>
  );
 }  
Conclusion

In this blog, we have learned to use useReducer along with useContext to manage the global state in react.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *