When to use native React.useReducer Hook and how it differentiate from Redux

So, Hooks are available from React 16.8. From their documentation, Hooks come as a replacer of state in functional components. The basic hooks are: useState, useEffect, useContext, but there are also some additional hooks, one of them being useReducer, and it looks like it uses the same action-dispatch architecture as Redux does.

The questions would be if it comes as a replacement of Redux because of the resemblance ?

Does it suits particular projects better ?

Where would it fit ?


Solution 1:

Redux is a library that encourages data flow in a specific manner.

react-redux on the other hand implements the React friendly approach and provides a lot middlewares and wrappers so that the library consumers do not have to set up the entire process on their own.

While useReducer is a part of how Redux works, it isn't Redux in its entirety. In order for you to use dispatch and state deep down in your components you would still have to use useContext and useReducer in a combination which would be like re-inventing the wheel.

On top of that useReducer just gives you a dispatch method which you can use to dispatch plain old objects as actions. There is no way yet to add middlewares to these such as thunk, saga and many more.

You also can have multiple reducers in your application using useReducer but then the way to combine these to form a single store still have to be managed by the developer.

Also React docs state that useReducer is an alternative to useState when state logic is complex

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.

What hooks like useContext, useReducer do is that they eliminate the dependency on Redux for small apps.

Solution 2:

So, if Redux and useReducer were to be compared

Redux:

  • centralised state
  • forges more de-coupling
  • has middlewares: Redux thunk and Redux logger
  • actions can only hit one Store
  • maybe more suitable for big projects

useReducer:

  • local state
  • no wrapper component
  • needs useContext in order to reinvent the wheel
  • comes with other native hooks
  • no extra dependencies needed
  • multiple stores maybe(actually reducers that can act as store)
  • maybe more suitable for small projects