What is the main difference between using React-Redux Hooks and React-Redux Connect()?

前端 未结 4 1828
醉话见心
醉话见心 2021-01-02 00:17

I am about to start a project with React-Redux. For the APIs references there are Hooks and connect(). Since, Hooks are the alternate of connect APIs. What is the difference

4条回答
  •  攒了一身酷
    2021-01-02 01:02

    React-Redux internally uses React Context to connect components to the store.

    The connect() function wraps your component into another component that connects to the store context and forwards the selected state to your component as props.

    If you called...

    const YourConnectedComponent = connect(mapStateToProps)(YourComponent)`
    

    ...you can imagine the wrapper to roughly look like this:

    const YourConnectedComponent = props => (
        
            {state => }
        
    );
    

    mapStateToProps in this case would be the function you provided to connect(). This is very simplified and it doesn't actually look exactly like this for various performance reasons but it is suitable to demonstrate the general concept.

    The useSelector hook also consumes the store context but without creating a component in between for that. It directly returns the selected state for the component to use it. It internally uses useContext which is "the hooks way" to consume a context.

    useDispatch just exposes dispatch() to your component for it to dispatch actions with it.

    Technically the outcome is more or less the same whether you are using hooks or connect().

提交回复
热议问题