useReducer hook best practice 2025

✅ useReducer Hook Best Practices in React JS 2025

The useReducer hook is useful for managing complex state logic. Here are best practices to follow:

  • ✅ Keep reducer logic pure (no side effects).
  • ✅ Define action types as constants to avoid typos.
  • ✅ Use a switch-case (or map object) for actions.
  • ✅ Group related state under a single reducer instead of multiple useState.
  • ✅ Always return the previous state if no action matches.
  • ✅ Use dispatch for state updates to make the flow clear.

🧠 Example: Counter using useReducer


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:
      return state;
  }
}

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

  return (
    

Count: {state.count}

); }

📌 When to use useReducer:

  • When state logic is complex or involves multiple sub-values.
  • When next state depends on the previous one.
  • When state logic is reused or tested in isolation.