JAVASCRIPT

Manage Complex State with useReducer

Master React's `useReducer` for complex state management. Centralize logic for states with multiple sub-values or intricate transitions, enhancing predictability.

import React, { useReducer } from 'react';

// Reducer function defines how state transitions based on actions
const counterReducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    case 'reset':
      return { count: action.payload || 0 }; // Optional payload for reset
    default:
      return state;
  }
};

function ComplexCounter() {
  // useReducer returns the current state and a dispatch function
  const [state, dispatch] = useReducer(counterReducer, { count: 0 });

  return (
    <div>
      <h2>Count: {state.count}</h2>
      <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: 'reset', payload: 100 })}>Reset to 100</button>
    </div>
  );
}

export default ComplexCounter;
How it works: This snippet demonstrates `useReducer`, a hook for managing state with more complex logic than `useState`. It takes a `reducer` function and an `initialState`, returning the current `state` and a `dispatch` function. The `reducer` function determines how the state changes based on dispatched `actions` (objects with a `type` property and optional `payload`). This pattern centralizes state update logic, making it more predictable and easier to test, especially for states that depend on previous values or have multiple related transitions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs