DEV Community

Athithya Sivasankarar
Athithya Sivasankarar

Posted on

useReducer in React

When building React applications, we often use useState to manage state. But when the state logic becomes more complex, React provides another Hook called useReducer.

useReducer helps us manage state changes in a more organized way by using a reducer function and actions.

What is useReducer?

useReducer is a React Hook used for state management.

It works similarly to Redux because it uses:

  1. State – Current data.
  2. Action – What operation should be performed.
  3. Reducer Function – Decides how the state should change.

Syntax

const [state, dispatch] = useReducer(reducerFunction, initialState);
Enter fullscreen mode Exit fullscreen mode

Parameters

  • reducerFunction → Function that updates the state.
  • initialState → Starting value of the state.

Returns

  • state → Current state value.
  • dispatch() → Function used to send actions to the reducer.

Example: Counter Application

Code

import React, { useReducer } from 'react'

function App() {

  function reducerFn(state, action) {
    switch (action.type) {
      case "increment":
        return { count: state.count + 1 }

      case "decrement":
        return { count: state.count - 1 }

      case "reset":
        return { count: 0 }

      default:
        return state
    }
  }

  const [state, dispatch] = useReducer(reducerFn, { count: 0 });

  return (
    <div>
      <h1>Count : {state.count}</h1>

      <button onClick={() => dispatch({ type: "increment" })}>
        +
      </button>

      <button onClick={() => dispatch({ type: "decrement" })}>
        -
      </button>

      <button onClick={() => dispatch({ type: "reset" })}>
        Reset
      </button>
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

When Should You Use useReducer?

Use useReducer when:

  • State logic becomes complex.
  • Multiple state updates are needed.
  • Different actions update the same state.
  • Building larger applications.

Top comments (0)