DEV Community

gaurbprajapati
gaurbprajapati

Posted on

A Beginner's Guide to the useReducer Hook in React.js

React.js is a popular JavaScript library for building user interfaces, and it provides several hooks that simplify state management. One of the most powerful hooks is useReducer, which offers a predictable way to manage complex state logic within a React component. In this tutorial, we will explore the code example provided and explain each concept in detail to help beginner developers understand the useReducer hook.

Let's dive into the code example provided and explain each concept step by step.

  1. usereducer.js:
import { useReducer } from "react";
import React from "react";

const initialState = 0;

export default function Usereducer() {
  function reducer(state, action) {
    switch (action.type) {
      case "increment":
        return state + 1;
      case "decrement":
        return state - 1;
      case "division":
        return state / 2;
      case "multiply":
        return state * 2;
      default:
        throw new Error();
    }
  }

  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      Hello Count: {state}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "division" })}> /</button>
      <button onClick={() => dispatch({ type: "multiply" })}>*</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Importing useReducer from the "react" module allows us to use the useReducer hook in our component.
  • initialState represents the initial value of the state, which in this case is set to 0.
  • The Usereducer function component is exported as the default export.
  • Inside the Usereducer component, we define the reducer function. This function takes the current state and an action as parameters.
  • The switch statement inside the reducer function checks the action.type to determine which case to execute. Based on the action type, the reducer returns a new state.
  • The component uses the useReducer hook by calling it with the reducer function (reducer) and the initial state (initialState). It returns an array with two elements: the current state (state) and the dispatch function (dispatch).
  • The component renders JSX that displays the current state value (Hello Count: {state}).
  • The four buttons have onClick handlers that dispatch actions with different types to modify the state.
  1. App.js:
import "./styles.css";
import Usereducer from "./component/Usereducer";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <h1>Hello sir ! </h1>
      <Usereducer />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The App component is the entry point of our application.
  • It imports the CSS styles from "./styles.css" (which you may have defined separately) to apply to the component.
  • It imports the Usereducer component from "./component/Usereducer" (relative path) to use it in the JSX.
  • The component renders JSX that displays some headings and includes the Usereducer component.
  1. index.js:
import { StrictMode } from "react";
import {

 createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The index.js file is responsible for rendering our application to the DOM.
  • It imports StrictMode from the "react" module, which helps highlight potential issues in the application during development.
  • It imports createRoot from the "react-dom/client" module to create a root element for rendering.
  • It imports the App component from "./App" (relative path) to use it as the main component of the application.
  • The rootElement variable represents the DOM element where the application will be rendered (identified by the "root" id).
  • createRoot is called with rootElement to create a root object for rendering.
  • root.render is used to render the App component inside the StrictMode wrapper, ensuring that the application runs in a strict mode.

Conclusion:
In this beginner's tutorial, we examined a code example that showcases the use of the useReducer hook in React.js. The code example can be accessed and experimented with at this CodeSandbox link.

The useReducer hook, along with reducers, is a powerful combination for managing state in React applications. By understanding how reducers work, developers can create predictable and maintainable state management systems. The example code demonstrated how to initialize state, define a reducer function, dispatch actions, and update the UI based on state changes.

Reducers play a vital role in the useReducer hook. They take the current state and an action as inputs and return a new state based on the action type. By organizing the state update logic into reducers, developers can easily understand and modify state behavior as their applications grow.

Understanding the useReducer hook and reducers empowers developers to build scalable and efficient React components. By following the principles outlined in this tutorial, beginners can establish a strong foundation in utilizing useReducer for effective state management.

Feel free to explore and experiment with the provided code example using the CodeSandbox link. Modify the code, add new actions, or incorporate additional features to further enhance your understanding of useReducer.

By incorporating the useReducer hook and understanding reducers, you'll be equipped with a powerful toolset to handle complex state logic in your React applications. Embrace the possibilities it offers and continue your journey into the world of React.js development. Happy coding!

Namaste coding!

Top comments (0)