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

前端 未结 4 546
一生所求
一生所求 2020-12-23 19:58

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,

4条回答
  •  离开以前
    2020-12-23 20:27

    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.

提交回复
热议问题