React Hook Quick Start

Hook Profile

React Hooks are React 16.7.0-alpha version introduced new features aimed at solving the state's share React problem. Call state sharing may not be very appropriate description, referred to the multiplexed state logic may be more appropriate, because React Hooks shared data processing logic only, and does not share the data itself. React in application development, configuration management is an essential component development content. Previously, in order to manage the state, the most common practice is to use a class components or the like directly redux state management framework. E.g:

class Hook extends React.Component {
  
constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
   return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

复制代码

Now, developers can directly use the State Hook React Hooks provided to deal with the state, class components for those that already exist, you can also use State Hook well reconstructed. E.g:

import React, { useState } from 'react';

function Hook() {
    const [count, setCount] = useState(0);

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

复制代码

It is found from the above example, Example assembly into a function, the function of this component has its own state, and also update their status. The reason may be doing so because of the use of useState, useState is react comes with a hook function, its role is to declare a state variable.

Hook API

All along, React in an effort to solve a problem that reuse problem state assembly. React In application development, we are through the components and data flows from top to bottom to be transferred into separate large view of the reusable components. But in the actual project development, reusable components with a business logic is still a problem. As we all know, React provides two ways to create a component, that is a function of class components and assemblies. Function component is a plain JavaScript function that takes an object and returns React props elements, functions, components more in line with the development of data-driven ideas React view. However, the function of the components has been because of a lack of class components for various characteristics such as status, life cycle, and because of these reasons are not a function of the component developer's favor, but Hooks is to allow the emergence of functional components that have the characteristics of the component. In order to function components that have the characteristics of components such as status, life cycle, React offers three core api, namely State Hooks, Effect Hooks and Custom Hooks. React useState is to provide the most basic, the most commonly used Hook, mainly used to define and manage local state. For example, the following useState implemented using a simple counter, as follows:

import React, { useState } from 'react'

function App() {
    const [count, setCount] = useState(0);
    return (
        <div>
            <button onClick={()=> setCount(count + 1)}>+</button>
            <span>{count}</span>
            <button onClick={() => setCount((count) => count - 1)}>-</button>
        </div>
    );
}

export default App;
复制代码

In the above example, a useState to define a state, class components different state, the state function component may be a basis for the object type value. useState returns an array, the first object array represents the current value of the state of the second object function representing a change in status, the setState similar class of the component. If a plurality of components function condition exists, either by a useState object type declaration state, the state may be declared more than once by useState. E.g:

//声明对象类型状态
const [count, setCount] = useState({
    count1: 0,
    count2: 0
});
 
//多次声明
const [count1, setCount1] = useState(0);
const [count2, setCount2] = useState(0);

复制代码

It can be found, compared to the declared object type state, more convenient way to declare state several times, mainly because the update function is replaced rather than the way adoption of the merger of the way. However, if the data to be processed nested logic function module, used useState becomes insufficient. Fortunately, developers can use useReducer React provided to deal with such problems. E.g:

import React, {useReducer} from 'react'

const reducer = function (state, action) {
    switch (action.type) {
        case "increment":
            return {count: state.count + 1};
        case "decrement":
            return {count: state.count - 1};
        default:
            return {count: state.count}
    }
};

function Example() {
    const [state, dispatch] = useReducer(reducer, {count: 0});
    const {count} = state;
    return (
        <div>
            <button onClick={() => dispatch({type: "increment"})}>+</button>
            <span>{count}</span>
            <button onClick={() => dispatch({type: "decrement"})}>-</button>
        </div>
    );
}

export default Example;

复制代码

Can be found, useReducer reducer function accepts two parameters and default values, and returns an array state and the current state of the dispatch function, consistent with the use Redux, except that the default value is Redux to a reducer through the function set default parameters given the way. useReducer Redux is no reason why use the default values ​​provided, that because React default state may be a function of the component from the props. E.g:

function Example({initialState = 0}) {
  const [state, dispatch] = useReducer(reducer, { count: initialState });
   ...
}

复制代码

Solve the problem of the internal function of the state assembly, the next problem to be solved is the function of the component lifecycle functions. In React functional programming ideas, the life cycle is a function of a bridge between functional and imperative, related operations can be performed based on the life cycle of function developers, such as network requests and operations DOM.

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

function Example() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        console.log('componentDidMount...')
console.log('componentDidUpdate...')
        return () => {
            console.log('componentWillUnmount...')
        }
    });

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

export default Example;

复制代码

Above code is executed, and then click the button performs the addition operation, as shown in the function call where the life cycle of FIG.

You can see, each time the callback function will useEffect the component update is called. And click on the button will trigger componentWillUnmount life cycle time of update, why destroy operation is performed prior to re-draw, in order to avoid memory leaks. Therefore useEffect can be regarded as a combination of componentDidMount, componentDidUpdate and componentWillUnmount and it is associated with the life cycle of a function component. Need to note is, componentDidMount or componentDidUpdate life cycle synchronization function class components are executed when the DOM updates, but useEffect and executes asynchronously when the DOM updated. Therefore, useEffect and does not block the browser update interface. If you need an analog synchronous execution lifecycle, you can use useLayoutEffect Hook React to offer.

Custom Hook

As we all know, the state should share some logic between classes is very troublesome components, conventional practices are addressed by the high-order components or properties of the function. However, the new version of React allows developers to create custom Hook to encapsulate the shared state logic, without the need to add new components to the component tree. The so-called custom Hook, in fact, refers to the beginning of the function name and call other functions that use the Hook, Hook defined from each state are completely independent. For example, following is an implementation example of axios network requests, as follows:

import axios from 'axios'

export const useAxios = (url, dependencies) => {

    const [isLoading, setIsLoading] = useState(false);
    const [response, setResponse] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        setIsLoading(true);
        axios.get(url).then((res) => {
            setIsLoading(false);
            setResponse(res);
        }).catch((err) => {
            setIsLoading(false);
            setError(err);
        });
    }, dependencies);
    return [isLoading, response, error];
};

复制代码

As indicated above, the development is to use requests axios Hook custom data. Using the methods and systems provided by Hook Similarly, you can directly call. E.g:

function Example() {
    let url = 'http://api.douban.com/v2/movie/in_theaters';
    const [isLoading, response, error] = useAxios(url, []);

    return (
        <div>
            {isLoading ? <div>loading...</div> :
                (error ? <div> There is an error happened </div> : <div> Success, {response} </div>)}
        </div>
    )
}

export default Example;

复制代码

Can be found, compared to the higher-order functions and properties of components, etc., custom Hook is more concise and easy to read, not only here, from component definition Hook hell does not cause the nesting problem. Although React of Hooks has many advantages. However, the process of using Hooks, the need to pay attention to the following points: • Do not use the Hook in circulation, conditions or nested function, and can only be used at the top level React Hook function. The reason to do so, because React need to use the correct call sequence to update the corresponding status, and call the appropriate function of the life cycle of a function. Hook or loop Once called the conditional branch statement, it is easy to lead to inconsistencies in the calling sequence, thereby to produce unpredictable consequences. • Only React functional components or custom Hook Hook in use. Meanwhile, in order to avoid low-level errors in development, you can install a plug-eslint install command as follows:

yarn add eslint-plugin-react-hooks --dev
复制代码

Then, add the following eslint some configuration in the configuration file.

{
  "plugins": [
    // ...
    "react-hooks"
  ],
  "rules": {
    // ...
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn"
  }
}

复制代码

React Hooks by means of the API provided, the function of most of the components may be implemented based on features and Hooks shared logic state, improve the reusability of assembly has certain advantages. It is foreseeable that, Hooks React will be an important direction for future development.

Reproduced in: https: //juejin.im/post/5cfeee766fb9a07ef06f8997

Guess you like

Origin blog.csdn.net/weixin_33736048/article/details/93174687