Mastering React State Management with useReducer: A Comprehensive Guide

Prashant Sharma - Feb 22 - - Dev Community

Introduction:
Hey DEV community! 👋 In this tutorial, we'll delve into the versatile useReducer hook in React and explore its capabilities in managing multiple states within a functional component. Today, we'll build a robust user management system with states for userId, userType, and userName. Let's get started!


1. Setting Up the React App:
Begin by creating a new React app using Create React App. Navigate to your project directory and run:

npx create-react-app use-reducer-tutorial
cd use-reducer-tutorial
Enter fullscreen mode Exit fullscreen mode

2. Create a Reducer:
Inside the src folder, create a file named userReducer.js. Define the reducer to handle user-related states:

// src/userReducer.js
const userReducer = (state, action) => {
  switch (action.type) {
    case 'SET_USER':
      return {
        ...state,
        userId: action.payload.userId,
        userType: action.payload.userType,
        userName: action.payload.userName,
      };
    default:
      return state;
  }
};

export default userReducer;
Enter fullscreen mode Exit fullscreen mode

3. Create the User Component:
In the src folder, create a file named User.js. Use useReducer to manage user-related states:

// src/User.js
import React, { useReducer } from 'react';
import userReducer from './userReducer';

const User = () => {
  const initialState = { userId: null, userType: null, userName: null };
  const [state, dispatch] = useReducer(userReducer, initialState);

  const setUser = () => {
    dispatch({
      type: 'SET_USER',
      payload: {
        userId: '123',
        userType: 'admin',
        userName: 'John Doe',
      },
    });
  };

  return (
    <div>
      <h1>User Information:</h1>
      <p>User ID: {state.userId}</p>
      <p>User Type: {state.userType}</p>
      <p>User Name: {state.userName}</p>
      <button onClick={setUser}>Set User</button>
    </div>
  );
};

export default User;
Enter fullscreen mode Exit fullscreen mode

4. Use the User Component in App.js:
Replace the content of src/App.js with the following:

// src/App.js
import React from 'react';
import User from './User';

function App() {
  return (
    <div className="App">
      <User />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

5. Run the Application:
Start your React app:

npm start
Enter fullscreen mode Exit fullscreen mode

Open your browser and go to http://localhost:3000 to see the user management system in action.


Conclusion:
In this tutorial, we've harnessed the power of useReducer to manage multiple states (userId, userType, userName) efficiently. The userReducer handles the logic, and the User component uses useReducer to manage and update user-related states. Feel free to adapt this example to more complex scenarios and elevate your React state management game!


Have you explored useReducer in your projects? Share your experiences below! Let's learn and grow together.


#React #StateManagement #useReducer #JavaScript #WebDev

. . . . . . . . . . . . . . .