19 Feb 2024




Intermediate

useReducer is a React.js hook that provides an alternative to useState for managing state in functional components. It is used for managing more complex state logic where the next state depends on the previous one and involves multiple sub-values. useReducer takes a reducer function and an initial state, returning the current state and a dispatch function to update the state based on actions dispatched to the reducer. This hook is particularly useful for managing state in components with intricate state transitions or logic.

Basic syntax of the useReducer hook using counter example:

1. Creating a Reducer Function (reducer.js):

// reducer.js

const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

export default reducer;
  • reducer: This is a function that takes two arguments:
    • state: The current state.
    • action: An object that describes the state change.

The reducer function evaluates the action type and returns a new state based on that action. It's important that the reducer function is a pure function, meaning it doesn't mutate the original state, but instead returns a new state object.

2. Using the useReducer Hook (Counter.js):

// Counter.js

import React, { useReducer } from 'react';
import reducer from './reducer';

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  const increment = () => {
    dispatch({ type: 'INCREMENT' });
  };

  const decrement = () => {
    dispatch({ type: 'DECREMENT' });
  };

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

export default Counter;

Syntax of useReducer:

const [state, dispatch] = useReducer(reducer, initialState);
  • useReducer: This is a hook provided by React. It takes a reducer function and an initial state as arguments, and returns the current state and a dispatch function.
  • initialState: This is the second argument passed to the useReducer hook. It defines the initial state of the component.
  • reducer: This is the first argument passed to useReducer. It's a function that defines how state transitions should occur in response to dispatched actions.
  • state: The current state managed by the reducer.
  • dispatch: This function is used to dispatch actions to the reducer. Actions are plain JavaScript objects that must have a type property which indicates the type of action being performed. Additional properties can be included in the action object to provide data necessary for updating the state.

3. App Component File (App.js):

// App.js

import React from 'react';
import Counter from './Counter';

function App() {
  return (
    <div>
      <h1>Counter App</h1>
      <Counter />
    </div>
  );
}

export default App;

Here's what happens with the useReducer hook:

  1. Initialization: You initialize the state using the useReducer hook by passing a reducer function and an initial state value. The reducer function takes the current state and an action, and returns the new state.

  2. Dispatching Actions: To update the state, you dispatch actions to the reducer function. Actions are plain JavaScript objects that describe the type of update you want to make to the state.

  3. Reducer Logic: Inside the reducer function, you switch on the action type and return the new state based on the action type and payload.

  4. State Updates: When an action is dispatched, React calls the reducer with the current state and the action. The reducer returns the new state, which then becomes the current state for the component.

useReducer is especially useful when dealing with complex state logic that involves multiple sub-values, or when the next state depends on the previous one, or when you have more complex update logic that can be encapsulated in a reducer function.

reactjs
usereducer