Skip to content
Advertisement

What’s the purpose of the 3rd argument in useReducer?

From the docs:

[init, the 3d argument] lets you extract the logic for calculating the initial state outside the reducer. This is also handy for resetting the state later in response to an action.

And the code:

JavaScript

Why would I do that over reusing a constant initialState?

JavaScript

Looks less verbose to me.

Advertisement

Answer

EDIT july 2020: React documentation has now better explainations on this arg called lazy initializer. Using this function in another way could result to breaking changes due to undocumented effect. Following answer remain valid.


As far as I can experiment, the init function as third arg is a transformer of the initialState.

It means that initialState will not be used a initial state, but as arg for init function. The return of this one will be the true initialState. It could be usefull to avoid huge param during the useReducer initialization line.

JavaScript
JavaScript
Advertisement