Using hooks with react-redux

26 August 2020

Offical documentation for react-redux hooks can be found here.

In these examples I'm using redux-thunk to call actions as functions instead of calling the type and payload.

import React, { useEffect } from "react"
import { connect } from "react-redux"
import { fetchAction } from "../actions/fetchActions"

// Redux state and actions brought in through props
// via mapStateToProps and connect
const component = ({
  state1,
  state2,
  state3,
  fetchAction
}) => {
  useEffect(() => {
    fetchAction();
  }, [])
}

const mapStateToProps = (state) => {
  state1,
  state2,
  state3,
}

export default connect(mapStateToProps, {fetchAction})

The useSelector and useDispatch hooks are used in the same fashion as the hooks provided by React. The useSelector hook takes an arrow function that is passed a state object which is the entire global state of the store. You select which part of that state to return.

useDispatch is assigned to a variable and then can be called anywhere that you need to dispatch an action.

import React, { useEffect } from "react"
import { useSelector, useDispatch } from "react-redux"
import { fetchAction } from "../actions/fetchActions"

const component = {
  // Using useSelector to access redux state
  const state1 = useSelector(state => state.state1);
  const state2 = useSelector(state => state.state2);
  const state3 = useSelector(state => state.state3);

  // The useDispatch hook lets you dispatch any action
  const distpatch = useDispatch();

  useEffect(() => {
    dispatch({fetchAction()});
  }, [])
}

export default component;

Using react-redux hooks is a lot cleaner because you don't have to connect the component, use mapStateToProps or pass actions through props. This makes development with typescript easier.