React Reducer Runs Twice

React Reducer Runs Twice

If using the react hook useReducer(reducer, state) and you notice it runs twice after dispatching an action - this is actually by design for development mode.

The reducer dispatches an action with a given state and returns a new state. It should never mutate the previous state.

If you follow this rule, you’ll never notice the reducer running twice. However if you are mutating the state and returning the new state based off that, you’ll make the mutation twice. So if you are adding something to a list in the state, you’ll see it added twice. This feature of react development keeps our functions pure. Pure functions are much easier to test.

See below for more information.

https://react.dev/reference/react/useReducer#my-reducer-or-initializer-function-runs-twice