← Back to all snippets
JAVASCRIPT

Managing Complex Component State with useReducer

Explore React's `useReducer` hook to manage more complex state logic, offering a scalable and predictable alternative to `useState` for multi-part states.

import { 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 'toggleText':
      return { ...state, showText: !state.showText };
    default:
      throw new Error();
  }
}

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

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
      <button onClick={() => dispatch({ type: 'toggleText' })}>Toggle Text</button>
      {state.showText && <p>This text can be toggled!</p>}
    </div>
  );
}
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 `initialState`, returning the current state and a `dispatch` function. The `dispatch` function is used to send 'actions' to the `reducer`, which then computes the new state based on the current state and the received action type, making state updates predictable and testable.

Need help integrating this into your project?

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

Hire DigitalCodeLabs