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:
function init(initialCount) {
return { count: initialCount };
}
function reducer(state, action) {
switch (action.type) {
...
case 'reset':
return init(action.payload);
...
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialCount, init);
...
}
Why would I do that over reusing a constant initialState
?
const initialState = {
count: 5,
};
function reducer(state, action) {
switch (action.type) {
...
case 'reset':
return initialState;
...
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialState);
...
}
Looks less verbose to me.
initialCount
is still present as the 2nd argument. – Enrolleereset
update for the initial count to be set, otherwise thecount
is null? – EnrolleeuseReducer(reducer, 0)
then init count is 0. Case 2useReducer(reducer, 7, n => 2 * n)
, then init count is 14. Is that clear? – Czechn => 2 * n
clarified it – Enrollee