useState vs useReducer
Introduction
This post does not deal with what a state and a reducer means as it is expected that the user has a little background on what they are and how they work.
This post mainly focusses on the doubts that a developer might encounter when they have to choose between a state and a reducer and not clear on when to use which feature.
useState =>
- This is a good state management tool (mainly used for component state)
- Suitable to manage individual states where the properties or data are simple like primitive values
- This is a good option for simple and less dependent data
Example:
When we have a input change like radio button that turns on / off the visibility of sections of the DOM, a state is a good fit
useReducer =>
- This is a good option when objects are used as a state
- This is a good option to use when there is a complex state update logic to be executed since there is dependency between the individual states
- This feature helps in moving out the state logic scattered in the component to a reducer, which gives better control and helps a lot in writing a readable, maintainable and single source of truth logic.
Example:
- When there are dependencies between the states and which are cumbersome to use when using the useState, where each time a change happens, we must have to watch for the change and do related cascade effects or changes
- We might consider a complex form where the user chooses the package and discount codes and we have to make sure that they are of the right combination so that the user can proceed with the operation, a reducer is a right choice
Comments
Post a Comment