← Back to all snippets
JAVASCRIPT

React useReducer for Complex State Logic

Master React's useReducer hook for managing more complex state logic than useState, using a reducer function to handle multiple state transitions efficiently.

import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    case 'reset':
      return initialState;
    default:
      throw new Error();
  }
}

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

  return (
    <div>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
    </div>
  );
}

export default Counter;
How it works: The `useReducer` hook is an alternative to `useState` for managing state, especially when state logic is more complex or involves multiple sub-values. It takes a reducer function and an initial state, returning the current state and a `dispatch` function. The `dispatch` function sends 'actions' to the reducer, which then computes the next state based on the current state and the action, making state transitions predictable and easier to test compared to multiple `useState` calls.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs