This article is by IMWeb IMWeb team

Itnext. IO /how-to-use…

React-redux has released version 7.1.0 of hooks. This means we can use the latest best practices in React.

Hooks let us write less code for the same functionality. The less code we have to write, the faster we can start the application.

Simple Redux components

This is a very basic and traditional Redux connected component. How would you refactor it using Hooks?

import React, { Component } from "react";
import { connect } from "react-redux";
import { toggleSwitch } from "./UiReducer";

class Toggle extends Component {
  render() {
    const { ui, toggleSwitch } = this.props;
    return (
      <div>
        <div>{JSON.stringify(ui)}</div>
        <input
          type="checkbox"
          value={ui.toggle}
          onChange={toggleSwitch}
        />
      </div>
    );
  }
}

const mapStateToProps = ({ ui }) => ({
  ui
});

export default connect(
  mapStateToProps,
  { toggleSwitch }
)(Toggle);
Copy the code

Above is a simple component that toggles check boxes. For simplicity, we only have one state, and toggle is a Boolean.

Toggle check boxes with Redux

If you know anything about hooks, you probably know that hooks need to be used in function components. You cannot use hooks in the React class.

Step 1 – Refactor the class component into a function component

Converting the React component from a class to a function component is fairly straightforward. All we have to do is

import React from "react";
import { connect } from "react-redux";
import { toggleSwitch } from "./UiReducer";

const Toggle = ({ ui, toggleSwitch }) = > (
  <div>
    <div>{JSON.stringify(ui)}</div>
    <input type="checkbox" value={ui.toggle} onChange={toggleSwitch} />
  </div>
);

const mapStateToProps = ({ ui }) => ({
  ui
});

export default connect(
  mapStateToProps,
  { toggleSwitch }
)(Toggle);
Copy the code

Note: This code is much shorter than the previous one. We replaced the class syntax with simpler function syntax. We also deconstructed the UI and toggleSwitch properties from the arrow function parameter props. To be sure, the switch still works as expected.

Hooks are usually prefixed with the use keyword, such as useState or useSelecor.

The way we currently read state from store is through mapStateToProps and encapsulate function components in Connect HOC.

Step 2 – useSelector

Let’s start by reading the state using hooks. We need to import useSelector from the React-Redux package. Using useSelector hook, we can read our state.

import React from "react";
import { connect, useSelector } from "react-redux";
import { toggleSwitch } from "./UiReducer";

const Toggle = ({ toggleSwitch }) = > {
  const ui = useSelector(state= > state.ui);
  return (
    <div>
      <div>{JSON.stringify(ui)}</div>
      <input type="checkbox" value={ui.toggle} onChange={toggleSwitch} />
    </div>
  );
};

export default connect(
  null,
  { toggleSwitch }
)(Toggle);
Copy the code

Note: We removed the UI parameters and used the useSelector hook. The first argument to useSelector is the state of the storage.

Step 3 – useDispatch

UseDispatch Hook lets us perform redux operations. We import the useDispatch hook from the React-Redux package.

Using useDispatch is relatively simple, and we store the hook instance under a variable. We can call the Dispatch function from any event listener.

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { TOGGLE } from "./UiReducer";

const Toggle = () => {
  const ui = useSelector(state => state.ui);
  const dispatch = useDispatch();
  return (
    <div>
      <div>{JSON.stringify(ui)}</div>
      <input
        type="checkbox"
        value={ui.toggle}
        onChange={() => dispatch({ type: TOGGLE })}
      />
    </div>
  );
};

export default Toggle;
Copy the code

Note: We call the dispatch function here using the type constant TOGGLE, which we define in the Redux constant and import into the component.

export const TOGGLE = "ui/toggle";
Copy the code

If you want to pass the payload to the Dispatcher, do this as usual.

dispatch({ type: TOGGLE, payload: 'My payload' })
Copy the code

conclusion

A: congratulations! You successfully refactored from the class to use hooks. To make sure everything works, let’s test the Toggle again.

Yes, everything is fine. Now that you know the basics of hooks and are using hooks and Redux, I encourage you to read the documentation to get a deeper understanding of these concepts.

In addition, I recommend reading Functional React: Quickstart with React Hooks, Redux and MobX for an in-depth understanding of Redux, React and MobX.

Pay attention to our

IMWeb team belongs to Tencent and is one of the most professional front-end teams in China.

We focus on the front-end field for many years, responsible for QQ information, QQ registration, QQ group and other billion business. Currently, it focuses on online education, and carefully hones three major products: Tencent Classroom, Penguin Tutoring and ABCMouse.

Community official website:

imweb.io/

Join us:

Careers.tencent.com/jobdesc.htm…

Scan code to pay attention to IMWeb front-end community public number, get the latest front-end good articles

Micro blog, nuggets, Github, Zhihu can search IMWeb or IMWeb team to follow us.