useReducer: dispatch causes rerender even if state is not changed useReducer: dispatch causes rerender even if state is not changed reactjs reactjs

useReducer: dispatch causes rerender even if state is not changed


In terms of your example as-is, it's not immediately obvious as to what is causing the component to re-render. However, the docs seem to suggest that it's not a guarantee that a re-render won't occur when you don't mutate the state:

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with useMemo.

This is why it's generally recommended that you run code that potentially has side effects in useEffect e.g.

const [state, dispatch] = useReducer(someReducer, 0);...useEffect(() => {  if (state === 0) {    dispatch({ type: 'SOME ACTION' });  }}, [state]);