useReducer() & useState() hooks, both of them are state management hooks which add interactivity in the app & component.
But sometimes, it can be complicated to distinguish which hook we should use and in which cases we should consider useReducer or useState. So here are some things which you can use to distinguish what to use:
For useState:
- Use it when you are dealing with JavaScript primitives as a state.
- Use it when you have simple logic to change the state.
- Use it when you don't want to separate business logic from the component.
- Use it when you have small applications. For example, taking input from the search field and then add it to the current state.
- Use it when you have different properties that don't affect each other or don't change each other in a correlated way.
- Use it when you have different state properties that can be managed by multiple state hooks easily, like a form submission.
For useReducer:
- Use it when you have JavaScript objects & arrays as the state.
- Use it when you have complex logic to change the state.
- Use it when you have a medium-sized application.
- Use it when you have different properties that are tied together then, these should be in one state object like a library management function (adding, issuing & removing book details)
- Use it when you have very complex business logic and hard to be done in component alone (help to avoid unnecessary deep nesting in the app component).
- Use it when you want to make the state more predictable.
Note (my views):
Reducer function in useReducer is like a functional programming paradigm because of several reasons:
- Pure function, takes input and always give an output
- Always return new state object, does not mutate the current state object (immutability)
- Outputs are predictable
- Binary in nature, takes two arguments (current state & action object) and return one state object as output
Top comments (0)