DEV Community

Himanshu Kanojiya
Himanshu Kanojiya

Posted on

Short checklist to decide when to useReducer & useState hook in the components

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:

  1. Use it when you are dealing with JavaScript primitives as a state.
  2. Use it when you have simple logic to change the state.
  3. Use it when you don't want to separate business logic from the component.
  4. Use it when you have small applications. For example, taking input from the search field and then add it to the current state.
  5. Use it when you have different properties that don't affect each other or don't change each other in a correlated way.
  6. Use it when you have different state properties that can be managed by multiple state hooks easily, like a form submission.

For useReducer:

  1. Use it when you have JavaScript objects & arrays as the state.
  2. Use it when you have complex logic to change the state.
  3. Use it when you have a medium-sized application.
  4. 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)
  5. 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).
  6. 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:

  1. Pure function, takes input and always give an output
  2. Always return new state object, does not mutate the current state object (immutability)
  3. Outputs are predictable
  4. Binary in nature, takes two arguments (current state & action object) and return one state object as output

Top comments (0)