React Redux Tutorials - 20 - useSelector Hook


useSelectoruseSelector is the hook which acts as a closed equivalent to the mapStateToProps function.
So it is used to get hold of any state that is maintained in the redux store.
const result: any = useSelector(selector: Function, equalityFn?: Function)
  • useSelector accepts a function as a parameter.
  • This function is called as a selector function.
  • This selector function receives the redux state as its argument.
  • The useSelector hook returns whatever is returned by this selector function.
  • import React from 'react'
    import {useSelector} from 'react-redux'
    
    function HooksCakeContainer() {
      
      const numOfCakes = useSelector(state => state.numOfCakes)
    
      return (
        <div>
          <h2>Num of cakes - {numOfCakes} </h2>
          <button>Buy cake</button>
        </div>
      )
    }
    
    export default HooksCakeContainer
    🖥
    Num of cakes - 10
    Buy cake