Super sexy react hooks (1): why she is unique


Super sexy react hooks (1): why she is unique

As the title shows, I’m going to write a series of articles about react hooks.

In the past half year, I have applied react hooks to many large projects, including five new refactorings and a small amount of other projects due to time.

These projects include

  • React Native
  • The application of the middle and background based on Ant Design Pro reconstruction
  • Taro application based on react, focusing on small program development
  • Web application based on create react app
  • Isomorphic application based on Beidou framework

So far, one of the projects, usestate, has been used 2053 times.

Super sexy react hooks (1): why she is unique

After using react hooks a lot, I have many things I want to share with you, which is also a summary of my growth in this year.

There are a lot of articles on the Internet that can teach us how to use react hooks, but few articles can guide us how to use them well. This is also the purpose of my summary.

This series of articles will not only simply introduce the API related to react hooks, nor go too deep into the source code to force the case. I will focus on practical application, and appropriately make the things that should be said easy to understand. It is also an effective test of whether you have a firm grasp of knowledge.

There will be many articles, which can only be written in spare time. It may take more than a month or even longer to finish. I hope that the students who are interested can have some patience. The article will give priority to my public address.Know nothing about attackPublished in China. This article first summarizes why react hooks are worth starting with and must not be missed.

Reading this series of articles requires a relatively solid JS foundation and a simple understanding of react. If you feel that you do not have such a condition, it doesn’t matter. Pay close attention to my public number. The series of advanced articles I have written before will surely help you lay a solid foundation.

Although this series of articles is mainly about the analysis of react hooks, they can also be used as an introductory course of react, and I will try to be easy to understand.

React hooks is a successful self subversion of react.

This is my real feeling after using react hooks a lot.

React teamAlways thinking about how to subvert yourself。 For the children’s shoes that mainly attack react, it’s really happy and painful.

And the feeling that react hooks gives me is undoubtedly that happiness is greater than pain.

1、 Simplicity visible to the naked eye

First, use a picture to compare:

Super sexy react hooks (1): why she is unique

The code on the left is the classic demo to learn about react.
The code on the right is to implement the same function in a new way.

Of course, simplicity is limited, not shocking enough, not persuasive enough.
Another example.

Based on the simple counting component above, the thought of forcibly setting a controlled component is shown in the figure below.

Super sexy react hooks (1): why she is unique

The number of lines of code is almost half.

import React, { useState, useEffect } from 'react';

interface Props {
  value: number,
  onChange: (num: number) => any

export default function Counter({ value, onChange }: Props) {
  const [count, setCount] = useState<number>(0);

  useEffect(() => {
    value && setCount(value);
  }, [value]);

  return [
    <div key="a">{count}</div>,
    <button key="b" onClick={() => onChange(count + 1)}>
      Click +1

I think everyone knows what it means to have less than half the code!

2、 Easier to get started

When a team chooses react as the main technology stack, it faces a big problem, that is, it is relatively difficult to recruit people < at least this is the case in Chengdu]. I have a deep understanding of this. Ten resumes, nine of them will be Vue, and one of them will be react, all of them are deceitful. In two years, I was surprised to find no one who will be react. Probably, we all think Vue is better to learn.

I found an article a long time ago to record my feelings when I first learned react.

Super sexy react hooks (1): why she is unique

At that time, I felt that it was difficult to learn react, and I thought I could not master it well, so I still wrote an article to persuade you to learn angular. Now it’s a little funny.

For beginners, it’s not easy to use react. What’s the difficulty? To sum up with my own experience:

Life cycle is hard to understand, more difficult to skillfully use

Super sexy react hooks (1): why she is unique

It’s relatively easy to remember the life cycle, but it’s another thing to apply it to practice. The life cycle of several runtimes is even more difficult to understand. And how to do performance optimization, these life cycle is the top priority. If you are not careful, the code you write may even cause the program to overturn.

It is necessary for a react developer to become a master to understand the life cycle correctly and use it skillfully.

But this is also the first obstacle on our way forward.

Mature and reliable component thinking, forming difficulties

Even if you have many years of development experience, it is possible that component-based thinking is not qualified. Bad component partitioning leads to bad code that is difficult to maintain.

Of course, this is not limited to react. All component-based thinking frameworks will have the same challenges. Component thinking is very important. It is the core of thinking at the bottom. With a better component-based thinking, the code written must be more elegant and maintainable. On the contrary, it may be a disaster.

Redux, the hottest state management solution, has many concepts and is hard to understand

Super sexy react hooks (1): why she is unique

Redux’s thinking is excellent, but it’s not easy to understand.
In addition, when many people study Redux, they all use Redux Chinese documents. I think it deepens the difficulty of learning. After learning it, they are confused!

Especially for self-taught students, they are likely to turn react away because of redux.

High level components are not easy to understand

Before react hooks comes out, high-level components are knowledge points that must be mastered in any case.

However, many students do not have solid basic knowledge, do not understand the higher-order functions, and have some small problems with object-oriented. When learning higher-order components, they naturally do not understand.

//Pass in the base component as a parameter
const withRouter = (Component) => {

  //Create intermediate components
  const C = (props) => {
    const { wrappedComponentRef, ...remainingProps } = props;
    return (
      <Route render={routeComponentProps => (
        //Wrappedcomponentref is used to solve the problem that higher-level components cannot get ref correctly
        <Component {...remainingProps} {...routeComponentProps} ref={wrappedComponentRef} />
      )} />

  C.displayName = `withRouter(${Component.displayName ||})`;
  C.WrappedComponent = Component;
  C.propTypes = {
    wrappedComponentRef: PropTypes.func

  //Hostesstatics is similar to object.assign, which is used to solve the problem that basic components lose static methods due to the wrapping of higher-level components
  return hoistStatics(C, Component);

export default withRouter;

Excellent solutions are in the community, many people can’t know for a long time with react

React itself is very simple, but there is no way to tell you a series of solutions around react. After learning react, you may not know how to use react to realize a walking lamp, or you may not know how to use react to realize a calendar.

Popular Redux and react router are not official solutions of react. More programs such as Redux chunk, Redux saga and so on, many react learners don’t know about these things. In this case, the cost of learning increases a lot in disguise.

Compared with the past, the emergence of react hooks has greatly reduced the learning cost of react. Specifically reflected in:

  1. The life cycle can be unlearned. React hooks uses a new concept to manage the operation of components.
  2. High level components need not be learned. React hooks can perfectly solve the problems that high-level components want to solve, and it is more reliable.
  3. Redux is no longer a must-have. We can manage component state in other ways.
3、 Great development experience

Function components have always been more popular than class syntax. But in the past, function components could not maintain their own state, so they had to choose class to achieve their goals in many cases.

React hooks makes it possible for function components to maintain internal state.

in my opinion,React hooks is the fastest way to realize the development in mind.

4、 Easier to combine with typescript

We hardly care how the react hooks component works with typescript. This is an advantage that class components do not have.

Many friends in the group are often confused when learning typescript. How to apply typescript to react? This kind of problem may be more confusing in higher-order components. I believe that the students who have suffered from this experience.

Even if you know how to solve it, it’s not that easy. For example, we try to use ts to clearly describe the data types passed in by the demo component props, and have to define additional interfaces.

import React from 'react';
import { connect } from 'net';

interface ConnectProps {
  dispatch: any,
  history: any

interface DemoProps {
  name: string,
  age: number

interface InjectedProps extends DemoProps, ConnectProps {}

export default class Demo() {
  get injected() {
    return this.props as 
  render() {
    return (
      <div>hello, world.</div>

The react hooks component, as a function component, hardly has such trouble. Like ordinary functions, it has no additional burden.

In general, react hooks is a comprehensive improvement of react development experience and a revolution of efficiency. If you’re using react and haven’t used react hooks yet, I’m sure it’s a pity for you.

Based on the principle of not forcing but not leading to war, this series of articles do not subjectively express any other opinions and opinions on the front-end framework such as Vue / angular. If you are complacent and boastful, please don’t think about it~

All cases of this series can be viewed in the following address

This series of articles is original, please do not reprint without permission, reprint please do believe me personally

Super sexy react hooks (1): why she is unique

I have written a book about how to learn JavaScript well. Students who are interested in it can click to read the original text for details.