React useReducer hook confusion


Not understanding what is the purpose of init being passed in useReducer hook here?

You can also create the initial state lazily. To do this, you can pass an init function as the third argument. The initial state will be set to init(initialArg) .

It 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:

It is explained here. That screen is an image from this page.

To put it a different way, in this trivial example, you could have skipped the third parameter and just given it:

const [state, dispatch] = useReducer(reducer, { count: initialCount });

But maybe you have something more complicated you want to do. Maybe you need it done in more than one place or at different times. That third parameter lets you give a function to transform the second parameter.

But you probably won’t need this in small apps. Technically you never need it, but if you have some complex initial state to set up, it could make your code cleaner.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.