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

前端 未结 4 1829
醉话见心
醉话见心 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 00:52

    connect is a High Order Component whose job is to provide a way to connect Redux's store to your components. useSelector and useDispatch are the equivalent hooks. Just another technique to do the same thing.

    class Component extends React.Component{
        componentDidMount(){
            const { fetchApi, arg } = this.props
            fetchApi(arg)
        }
    }
    const mapDispatchToProps = dispatch =>({
        fetchApi : arg => dispatch(fetchApi(arg))
    })
    const mapStateToProps = state =>({
        arg : state.arg
    })
    
    export default connect(mapStateToProps, mapDispatchToProps)(Component)
    

    Now the equivalent using hooks

    const Component = () =>{
        const dispatch = useDispatch()
        const arg = useSelector(state => state.arg)
    
        useEffect(() =>{
           dispatch(fetchApi(arg))
        },[dispatch, arg])
    }
    

    Both do exactly the same thing, it's only a different approach to connect redux to components internal state. Both consume Redux's context to expose dispatch and state inside a given component

提交回复
热议问题