useReducer Hook

  • This lesson introduces the useReducer Hook and explains how it helps manage complex state in React applications.

  • What is useReducer?

    useReducer is used for complex state logic.

    Best when:

    • Multiple state values

    • Complex updates

    • Predictable state change

    Reducer Function

    A reducer is a pure function.

    Syntax:

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    default:
      return state;
  }
}
  • Usage:

const [state, dispatch] = useReducer(reducer, { count: 0 });
  • dispatch sends actions.

    useReducer vs useState

    useState

    useReducer

    Simple state

    Complex logic

    Easy syntax

    Structured updates

    Local state

    Large applications

    useReducer is preferred in advanced apps.