EasyHooks📖 Theory Question

What is useReducer and when should you use it over useState?

💡

Hint

Complex state logic with multiple sub-values or when next state depends on action type — like Redux at component level

Full Answer

const [state, dispatch] = useReducer(reducer, initialState);
const initialState = { count: 0, loading: false, error: null };

function reducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':   return { ...state, count: state.count + 1 };
    case 'SET_LOADING': return { ...state, loading: action.payload };
    case 'SET_ERROR':   return { ...state, error: action.payload };
    case 'RESET':       return initialState;
    default:            return state;
  }
}

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

Choose useReducer when:

  • Multiple related state values that change together
  • Next state depends on action type, not just a single value
  • Complex state transition logic you want to test independently
  • State transitions need to be auditable (dispatch history)
💡 useReducer + useContext is a lightweight Redux alternative. Put dispatch in context — it's stable (never changes) so context consumers won't re-render unnecessarily when state changes.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint