Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React TypeScript: TS Error when using useReducer

Here is my code:

const Component = () => {
  const [count, increase] = useReducer(v => v + 1, 0);
  const handleClick = useCallback(
    () => {
      // TS2554: Expected 1 arguments, but got 0.
      increase();
    },
    []
  );
  return <>{count}<button onClick={handleClick}>Click Me</button></>;
}

Is this some bug in @types/react?

I think it should be:

type Dispatch<A> = (value?: A) => void;

instead of

type Dispatch<A> = (value: A) => void;
like image 995
dancerphil Avatar asked Oct 28 '25 08:10

dancerphil


1 Answers

A dispatch function always needs an action, which should be your second parameter in your reducer:

const [count, increase] = useReducer((v, action) => v + 1, 0);

The reason being so you can switch over action.type and handle each case accordingly. For example:

const [count, dispatch] = useReducer((state, action) => {
  switch(action.type) {
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    default:
      return state;
  }
}, 0);

And then you call it like:

dispatch({ type: 'increment' });

That's why dispatch requires one argument. More information: Hooks API Reference (useReducer)

For your case I suggest using a useState instead:

const [count, setCount] = useState(0);
const increase = () => {
  setCount(prev => prev + 1);
}
like image 63
Damien Flury Avatar answered Oct 29 '25 22:10

Damien Flury