Tip - When to use useReducer hook in React

react
Back
const [state, dispatch] = useReducer(reducer, initialState, lazyInitState);

Here are the basic rules we can follow while choosing between them

Example

We have 2 independent states like below

const [refreshDashboard, setRefreshDashboard] = useState<boolean>(false);
const [hasInternetConnection, setHasInternetConnection] = useState<boolean>(
true,
);

Let's say our user state is depends on accounts

const stateReducer = (state, action) => {
switch (action.type) {
case SET_USER: {
return {
...state,
user: {
...action.payload,
}
numberOfAccounts: state.accounts.length,
};
}
default: {
throw new Error(`Unhandled action type: ${action.type}`);
}
}
};
const [state, dispatch] = useReducer(stateReducer, {
user: { id: 1, numberOfAccounts: 0 },
accounts: [],
});

So useReducer is usually preferable to useState when:

Thanks!

MIT © Mohan Dere.
-