Sobes.tech
Middle+

Tell me about useReducer — what is its purpose and how does it work?

sobes.tech AI

Answer from AI

useReducer is a hook in React used for managing component state, especially when update logic is complex or depends on previous state.

It operates on the principle of a reducer from Redux: it takes the current state and an action, and returns a new state. This allows centralizing state update logic in one function.

Example of usage:

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

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

  return (
    <>
      <p>Counter: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </>
  );
}

Thus, useReducer helps better structure state updates, especially when there are many and they depend on different action types.