Learn about the hooks introduced by react in 10 minutes

Source: Internet
Author: User

Tag: Date () DoS service is supported.

"Hello everyone, I am Gu amo. Today I want to introduce it...". Hahaha, I thought of this beginning when I saw this question. Recently, react officially announced at the 2018 reactconf conference that react v16.7.0-Alpha will be introduced into hooks. Therefore, it is necessary for us to understand hooks and the problems arising therefrom.

Of course, the best and most direct way to learn is to read the document. Therefore, I strongly recommend that you read the document as an official document instead of a Chinese document. This article is also based onConclusion and consideration, The landlord will take the recently learnedStep by step, as concise as possibleTo help you. The shortcomings can be added in the comment area. This article will cover the following aspects:

  1. Why is hooks introduced?
  2. Hooks usage and precautions
  3. How does hooks solve existing problems?
  4. Questions raised when Hooks is introduced
Why is hooks introduced?

The official motive provided by react is to solve some unavoidable problems encountered during the long-term use and maintenance of react. For example:

  1. State-related logic in components that are difficult to reuse and share
  2. Complex logic componentsIt is difficult to develop and maintain. When our components need to process multiple irrelevant local states, each lifecycle function may contain various irrelevant logics.
  3. This in Class components increases learning costs, and Class components have some problems in optimization based on existing tools.
  4. Due to business changes, function components have to be changed to Class components.

Before learning more, we need to quickly understand some basic hooks usage.

Quick introduction to hooks

Hooks gives our function components the features of similar class components, such as local state and lifecycle. It also solves a series of problems mentioned above and how it solves these problems, it will be pointed out in detail below. First, let's take a quick look at the usage of Hoos. Here we will talk about the two most important hooks: usestate and useeffect. Let's first look at an example that you may have seen many times.

import { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
  return (
      <p> {count} </p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
  );
}
Usestate

Usestate can bring local state to our function component. It receives a value for the initial state and returns a pair of variables.

Const [count, setCount] = useState(0);

/ / equivalent to the
Var const = useState (0) [0]; / / this state
Var setConst = useState (0) [1]; // modify the method of this state
Useeffect

Useeffect can use the local state in our component for some operations with side effects

useEffect(() => {
  document.title = `You clicked ${count} times`;
});

In useeffect, you can also pass in the second parameter to determine whether to perform the operation to avoid unnecessary performance loss, as long as the value of the member in the second parameter array is not changed, this execution will be skipped. If an empty array [] is input, the effect will only be executed during the component mount and unmount periods.

useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]; / / if the count does not change, skip this execution

Useeffect also allows the function to return a function to clean up, such as canceling the subscription.

useEffect(() => {
  api.subscribe(theId);
  return () => {
      api.unsubscribe(theId)    //clean up
  }
});

When Will useeffect be executed?It will be executed during component mount and unmount and each re-rendering, that is, it will be executed during componentdidmount, componentdidupdate, and componentwillunmount.

When will the cleanup function be executed?It will be executed after the previous effect execution, before the next effect execution, and during the unmount Period

Notes

We can onlyFunction componentsUsing hooks, we can also use multiple groups of hooks in a component. For example:

function FriendStatusWithCounter(props) {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  const [isOnline, setIsOnline] = useState(null);
  useEffect(() => {
    API.subscribe(props.friend.id);
    return () => {
      API.unsubscribe(props.friend.id);
    };
  });

  return isOnline
}

But here we need to note thatWe can only call hooks in top-level codeIt cannot be called in the loop or judgment statement, so that our hooks will followSame OrderCall, because there is a key problem, that isUsestate needs to match the State based on the call sequence of the first rendering.Otherwise, usestate will not return the correct state for it.

Problems solved by hooks

Now that we know the basic usage of hooks, we can learn how hooks solves the long-term problems of react.

How to solve stateful logic reuse and sharing issues.

In the past, there were two solutions for similar problems:

  • Render props accepts a function that returns react element through props to dynamically determine the rendering result;
<DataProvider render={data => (
  <h1>Hello {data.target}</h1>
)}/>
  • In addition, higher-order components is similarFactory ModelTo produce components with the same or similar logic.
function getComponent(WrappedComponent) {

  return class extends React.Component {
    constructor(props) {
      super(props);
    }
    componentDidMount() {
      // doSomething
    }
    componentWillUnmount() {
      // doSomething
    }
    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
}

However, either method will increase the number of components, modify the component tree structure, and possibly cause wrapper hell. NowReact solves this problem through custom hooks.

Custom hooks

Custom Hooks is not an API, but a rule. The specific implementation is to use a function to encapsulate stateful logic and extract the logic from the component. In this function, we can use other hooks, test them independently, or even contribute them to the community.

import { useState, useEffect } from 'react';

function useCount() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
  
  return count
}

For example, in the preceding example, custom hooks extracts the Count operation. Here we need to follow a Convention to use the nameuse*This is to facilitate our differentiation and facilitate our maintenance. We can see that it is actually a function,We can reference it in all other existing components.

function CountStatus() {
  const count = useCount();
  return count;
}

The core concept here is to extract the logic and encapsulate it in custom hooks. Then, you can share the logic among any other components and contribute it to the community. So I also predicted that many imaginative custom hooks will appear in the Community in the near future, greatly improving our development efficiency.

Development and maintenance of components with complex logic

As we mentioned above, our components may become more and more complex as development progresses, and more local states need to be processed, therefore, the life cycle functions of components will be filled with various irrelevant logics. here we need to introduce a complicated official example. Let's first look at the situation of previous class components:

class FriendStatusWithCounter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0, isOnline: null };
    this.handleStatusChange = this.handleStatusChange.bind(this);
  }

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
    ChatAPI.subscribeToFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }

  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  componentWillUnmount() {
    ChatAPI.unsubscribeFromFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }

  handleStatusChange(status) {
    this.setState({
      isOnline: status.isOnline
    });
  }
  // ...

After hook Transformation:

function FriendStatusWithCounter(props) {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  const [isOnline, setIsOnline] = useState(null);
  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }
  // ...
}

Status and related processing logic can be divided by function, without having to be dispersed in various lifecycles, greatly reducing the difficulty of development and maintenance. In addition to these hooks, there are other additional hooks. Continue to learn about hooks api reference

Thoughts on hooks

Hooks expands the functions of our function components and features similar to those of Class components. It even avoids various problems of Class components, so there will be various questions, such

  • After Hooks is introduced, how do I select function components and Class components? The official reply to similar questions is:
Our goal is for hooks to cover all use cases for classes as soon as possible. There are no hook equivalents to the uncommon getsnapshotbeforeupdate and componentdidcatch lifecycles yet, but we plan to add them soon.

It is a very early time for Hooks, so some integrations like devtools support or flow/typescript typings may not be ready yet. some third-party libraries might also not be compatible with hooks at the moment.

The official goal is to allow hooks to cover all the class component cases as quickly as possible, but hooks is still in an early stage, various debugging tools and third-party libraries are not yet fully supported by hooks, and currently there is no hooks that can replace getsnapshotbeforeupdate and componentdidcatch in Class components, but they will soon be added. In general, we encourage you to use hooks in the future. You do not have to rewrite existing class components on a large scale. The hooks and hooks ecosystems will continue to improve.

  • Can hooks replace render-props and higher-order components? As we mentioned earlier, hooks can solve various problems caused by the latter. Can hooks replace the latter? Official answer:
Often, render props and higher-order components render only a single child. we think hooks are a simpler way to serve this use case. there is still a place for both patterns (for example, a virtual scroller component might have a renderitem prop, or a visual container component might have its own Dom structure ). but in most cases, hooks will be sufficient and can help reduce nesting in your tree.

In most cases, Hooks is sufficient and suitable, so Hooks is preferred.

This is two of my concerns after seeing hooks. If you want to learn more, go to the hooks FAQ. If you have any questions or want to add them, please refer to the comments area.

Original article address: 1190000016886795

Learn about the hooks introduced by react in 10 minutes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.