React hooks (hook function)

1, Why are there Hooks

        Before introducing Hooks, let's first talk about the creation methods of React components. One is class components and the other is pure function components. Moreover, the React team hopes that the components will not become complex containers, and it's better to just be a pipeline of data flow. Developers can combine pipes as needed. In other words, the best way to write a component should be a function, not a class.
However, we know that there are great differences between class components and pure function components in previous development. Pure function components have many characteristics that class components do not have:

  • A pure function component has no state
  • Pure functional components have no lifecycle
  • Pure function components do not have this
            It is doomed that the function components we advocate can only be used for UI display. When it comes to state management and switching, we have to use class components. In order to solve the problem that class components have complete functions but are very heavy, pure functions are very lightweight, but they have the above major limitations, React
    Team designed React Hooks. React Hooks is an enhanced function component. We can write a fully functional component without using class at all.

2, The meaning of Hooks

       ' The word Hooks' means "hook".
        React Hooks means that components should be written as pure functions. If external functions and side effects are needed, hooks should be used to "hook" the external code. And React Hooks are what we call "hooks".
        The following are the default four most commonly used hooks provided by React Hooks:

  • useState()
  • useContext()
  • useReducer()
  • useEffect()
            Different hooks introduce different external functions for functions. The above four hooks are prefixed with use. According to the React Hooks convention, all hooks are named with use prefix. Therefore, all hooks defined by yourself should be named useXXX.

3, React Hooks usage

1,useState()

        Pure function components have no state. useState() is used to introduce state for function components. In usestate (), it accepts the initial value of the state as a parameter, where the first item of the array is a variable, pointing to the current value of the state, similar to this.state; The second item is a function to update the state, similar to setState. The naming convention of this function is set prefix plus variable name of state.

Example - counter:

import React,{ useState } from "react";

const NewCount = ()=> {
    const [ count,setCount ] = useState(0)
    const addCount= ()=> {
        let newCount = count;
        setCount(newCount +=1)
    }
   return (
       <>
           <p> { count }</p>
           <button onClick={ addCount }>Count++</button>
       </>
   )
}
export default NewCount;

2,useContext()

        The function of the shared state hook is to distribute states. It is supported after React16.X to avoid react transmitting data layer by layer through Props.

Example - share status:

import React, { useContext } from "react";
const HookTest = ()=> {
    const AppContext = React.createContext({});
    const A = ()=> {
        const { name } = useContext(AppContext)
        return (
            <p>
                I am A assembly,The name is:{ name };
            </p>
        )
    }
    const B= ()=> {
        const { name } = useContext(AppContext);
        return (
            <p>I am B assembly,The name is: { name }</p>
        )
    }
    return (
        <AppContext.Provider value={{ name: 'Chuan Xiong Zhou'}}>
            <A />
            <B />
        </AppContext.Provider>
    )
}
export default HookTest;

3,useReducer()

        useReducer(): action hook. In the process of using React, if you encounter state management, you will generally use redux, but React itself does not provide state management. Usereducer () provides state management. First of all, as we all know about redux, its principle is that the user initiates an action in the page, so as to change the state through the reducer method, so as to realize the communication between the page and the state. The form of reducer is (state, action) = > newstate. The usereducer () of Hooks is as follows:
const [state, dispatch] = useReducer(reducer, initialState)
It accepts the reducer function and the initial value of the state as parameters and returns an array, in which the first item is the current state value and the second item is the dispatch function that sends the action.

4,useEffect()

        Side effect hook. It can be used to better handle side effects, such as asynchronous requests. Hooks' useEffect() also provides hooks for function components to handle side effects. In class components, we will put the request in componentDidMount. In function components, we can use useEffect(). Its specific usage is as follows
useEffect(() => {},[array])
        useEffect() accepts two parameters. The first parameter is the asynchronous operation to be performed, and the second parameter is an array, which is used to give the dependency of Effect. As long as the array changes, useEffect() will execute. When the second item is omitted, useEffect() will be executed every time the component is rendered. This is similar to the componentDidMount of a class component.

Example: simulate an asynchronous load of data through useEffect().

import React,{ useState,useEffect } from "react";
const AsyncPage = () => {
    const [loading,setLoading] = useState(true)
    useEffect(()=> {
        setTimeout(()=> {
            setLoading(false)
        },5000)
    })
    return (
        loading? <p>loading...</p>: <p>Asynchronous request complete</p>
    )
}
export default AsyncPage;

4, Create your own Hooks

        The above describes the default React Hooks provided to us by the four most commonly used React Hooks. Sometimes we need to create the Hooks we want to meet more convenient development, that is, assemble the above four Hooks according to the business scenario to get Hooks that meet our needs.
For example:

import React,{ useState,useEffect } from "react";
const usePerson = ({name}) => {
    const [loading, setLoading] = useState(true)
    const [person, setPerson] = useState({})

    useEffect(() => {
        setLoading(true)
        setTimeout(()=> {
            setLoading(false)
            setPerson({name})
        },2000)
    },[name])
    return [loading,person]
}
const AsyncPage = (name)=> {
    const [loading,person] = usePerson(name)
    return (
        <>
            {loading?<p>Loading...</p>:<p>{ person.name }</p>}
        </>
    )
}

const PersonPage = ()=> {
    const [state,setState] = useState('')
    const changeName = (name)=> {
        setState(name)
    }
    return (
        <>
            <AsyncPage name={ state } />
            <button onClick={ ()=> { changeName('Guo Jing')}}>Guo Jing</button>
            <button onClick={ ()=> { changeName('Huang Rong')}}>Huang Rong</button>
        </>
    )
}
export default PersonPage;

        In the above code, the previous examples are encapsulated into their own Hooks for easy sharing. Among them, usePerson() is a custom Hooks. It accepts a string and returns an array. The array includes the states of two data. Later, when using usePerson(), it will return different states according to the passed parameters, and then it can be easily applied to our page.

Keywords: Javascript html5 React

Added by ragefu on Mon, 11 Oct 2021 06:04:49 +0300