DEV Community

Prashant Sharma
Prashant Sharma

Posted on

1

Mastering React State Management with useReducer: A Comprehensive Guide

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

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay