← Back to all snippets
JAVASCRIPT

Managing Complex State with useReducer Hook

Learn how to use React's `useReducer` hook for managing complex state logic more effectively than `useState`, ideal for scenarios with multiple related state transitions.

import React, { useReducer } from 'react';

const initialState = { count: 0, showText: true };

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

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

  return (
    <div>
      <h1>Count: {state.count}</h1>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
      <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
      <button onClick={() => dispatch({ type: 'toggleText' })}>Toggle Text</button>
      {state.showText && <p>This text can be toggled!</p>}
    </div>
  );
}

export default CounterWithReducer;
How it works: The `useReducer` hook is an alternative to `useState` for managing more complex state logic that involves multiple sub-values or when the next state depends on the previous one. It takes a reducer function and an initial state, returning the current state and a `dispatch` function. The `dispatch` function accepts an action object, which is then processed by the reducer to compute and return the new state, leading to a more predictable state management pattern.

Need help integrating this into your project?

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

Hire DigitalCodeLabs