As the title suggests, I’m going to write a series of articles about React Hooks.

In the last six months or so, I have implemented React Hooks on a number of large projects, 5 of which are new refactorings, the rest of which are used only a little bit due to time.

These projects include

  • React Native
  • Background application based on Ant-Design-Pro reconstruction
  • Taro app, based on React, focuses on small application development
  • A self-built Web application based on create-React-app
  • The isomorphism application of transformation based on Beidou framework

So far, one project, useState, has been used 2,053 times.

After using a lot of React Hooks, THERE’s a lot I’d like to share with you to sort of sum up my year.

There are plenty of articles on the Internet that teach you how to use React hooks, but very few on how to use them well. And this is also the purpose of my summary.

This series of articles will not simply cover the React Hooks related apis, nor will I delve too deeply into the source code for the sake of the react-hooks. I will focus on practical applications and getting exactly what needs to be said in plain English. It is also an effective test of whether they have a firm grasp of knowledge.

There will be a lot of articles, can only use spare time to write, it may take more than a month or even more to finish, I hope interested students can have a little patience, the article will be priority in my public number do not know non attack published. Here’s why React Hooks are worth getting started on, and should not be missed.

To read this series, you need to have a relatively solid JS foundation and a basic understanding of React. If you think you do not have such conditions, it does not matter, pay attention to my public number, I wrote before the basic advanced series of articles will be able to help you lay a solid foundation.

This series of articles, while primarily analyzing React hooks, can also be used as a primer on React. I will try to keep it simple.

React Hooks were a successful self-subversion by React.

This is how I really feel after using a lot of React Hooks.

The React team is always thinking about subverting themselves. For the React kids, it’s really both happy and painful.

And React Hooks made me feel more happy than hurt.

First, visible simplicity

Here’s a quick comparison:

The code on the left is a classic demo to learn how to React. The code on the right implements the same functionality in a new way.

Of course, conciseness is limited, not shocking enough, persuasive enough. Let’s do another example.

Based on the simple counting component above, force the thinking of a controlled component, as shown below.

The number of lines of code dropped by 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 < / button >]}Copy the code

I think we all know what half the code means!

Second, it’s easier to get started

When a team chose to React as the main technology stack, one of the major problems, is hiring relatively difficult < at least chengdu >, this, I have experience greatly, 10 to resume, nine are will vue, there is a will React, are deceptive, 2 years, I don’t recruit a person will React. Presumably, everyone thinks vUE is easier to learn.

I found an article from a long time ago and recorded my feelings when I first learned React.

At that time, I thought it was difficult to learn React, so I wrote articles urging people to learn Angular. It’s kind of funny now that I think about it.

React isn’t easy for beginners to learn. What’s so hard about React? To sum up from my own experience:

Life cycles are hard to understand and even harder to master

It’s relatively easy to memorize life cycles, but putting them into practice is another matter. The life cycles of several runtimes are even more difficult to understand. And how to do performance optimization, these life cycles are the most important. If you’re not careful, you can even write code that causes your program to flip over.

Being able to understand the life cycle and use it well is essential for React developers to become experts.

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

Mature reliable componentization thinking, form difficult

Even with years of development experience, componentized thinking may not pass muster. Bad component partitioning results in bad code that is difficult to maintain.

Of course, this is not limited to React. All componentized frameworks face the same challenges. Componentized thinking is very important, it’s the lowest core of thinking. Better componentized thinking leads to more elegant and maintainable code. Otherwise, it could be a disaster.

Redux, the most popular state management solution, is too conceptual to understand

Redux’s thinking is excellent, but it’s not easy to understand. In addition, many people learn Redux through Redux Chinese documents. I think it makes learning more difficult and makes people confused after learning it!

Students who are self-taught, in particular, will probably be shut out of React because of Redux.

Higher-order components are not easy to understand

Advanced components are something that must be learned anyway until React Hooks come out.

However, many students do not have solid basic knowledge, higher-order functions do not understand, object-oriented also have a little problem, when learning higher-order components of nature is also vaguely understand.

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

  // Create an intermediate component
  const C = (props) = > {
    const{ wrappedComponentRef, ... remainingProps } = props;return(<Route render={routeComponentProps => (// wrappedComponentRef) <Route render={routeComponentProps => remainingProps} {... routeComponentProps} ref={wrappedComponentRef} /> )} /> ) } C.displayName = `withRouter(${Component.displayName || Component.name})`; C.WrappedComponent = Component; C.propTypes = { wrappedComponentRef: Proptypes.func} // hoistStatics is similar to object.assign, which solves the problem of base components losing static methods due to higher-order Component wrapping. Return hoistStatics(C, Component); } export default withRouter;Copy the code

The best solutions were in the community, and many people didn’t know about React for a long time

React itself was very simple, but there was no way to tell people about the solutions around React. React implements a calendar, but you may not know how to implement a calendar with React.

Redux and React-Router are not official React solutions. There are more solutions like Redux Chunk, Redux Saga, etc. Many React learners don’t know about these. In this case, the cost of learning will increase a lot.

React hooks make learning React much cheaper than it used to be. Specifically reflected as:

  1. You don’t have to learn the life cycle. React Hooks use a new concept to manage the process of components.
  2. Don’t learn advanced components. React hooks are perfect for solving problems that higher-order components are trying to solve, and more reliably.
  3. Redux is no longer a must. We can manage component state in other ways.
3. Great development experience

Function components have always been more popular than class syntax. But previously functional components could not maintain their own state, so many times they had to choose class for their purposes.

React Hooks make it possible for function components to maintain internal state.

React Hooks, in my opinion, are the fastest way to do what I have in mind.

Fourth, it’s easier to combine with Typescript

There is little concern about how the React hooks component works with typescript. This is an advantage that class components do not have.

A lot of people in the community get confused when learning typescript: How to apply typescript to React? This problem can be even more confusing with higher-order components. I believe that the students have eaten this bitter experience.

Even if you know how to solve it, it’s not that easy. For example, if we were trying to use TS to clearly describe the data type passed in by the Demo component props, we had to define an extra interface.

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 {}

@connect
export default class Demo(a){
  get injected() {
    return this.props as 
  }
  render() {
    return (
      <div>hello, world.</div>)}}Copy the code

The React Hooks component, as a function component, has few such concerns. It’s just like a normal function, with no additional burden.

Overall, React Hooks are an overhaul of the React development experience and a revolution in efficiency. If you’re using React without using React Hooks, I’m sure that’s a shame for you.

In keeping with the principle of “no pretension”, this series of articles is subjectively free of any other comments or opinions on front-end frameworks such as Vue/Angular. If there is complacency, brag about the place, do not think about this ~

All examples in this article series can be viewed at the address below

Github.com/advance-cou…

This series of articles for the original, do not reprint, reprint please be sure to private letter me