← React Beginner Questions - Set 3 Q27

What is the difference between useState and useReducer?

React Beginner Questions - Set 3

Same primitive underneath. `useReducer` wins when the next state depends on several fields or when the transitions deserve names.

Example

import { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'add':    return { ...state, items: [...state.items, action.item], total: state.total + action.price };
    case 'clear':  return { items: [], total: 0 };
    default:       return state;
  }
}

export default function Cart() {
  const [state, dispatch] = useReducer(reducer, { items: [], total: 0 });

  return (
    <>
      <button onClick={() => dispatch({ type: 'add', item: 'Lamp', price: 20 })}>Add</button>
      <button onClick={() => dispatch({ type: 'clear' })}>Clear</button>
      <p>{state.items.length} items — ${state.total}</p>
    </>
  );
}

What to notice

← Back to the question list