Using hooks with react-redux

August 26, 2020

react-redux logo

Official 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})(component)

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 dispatch = 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.