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 ?
The main difference is that Redux creates one global state container which is above your whole application and is called a store and useReducer creates an independent component co-located state container within your component.
useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks. React guarantees that dispatch function identity is stable and won't change on re-renders.
The useReducer Hook accepts two arguments. The reducer function contains your custom state logic and the initialState can be a simple value but generally will contain an object. The useReducer Hook returns the current state and a dispatch method.
useReducer provides more predictable state transitions than useState , which becomes more important when state changes become so complex that you want to have one place to manage state, like the render function.
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 touseState
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With