Use records of react hooks

"Summary of the hooks of react"
react-hooks:
Common: useState, useEffect, useMemo, useRef, useCallback, useContext
Rare, useReducer, useImperativeHandle, useDebugValue, useTransition, uselayouteeffect

useState
Because functional components do not have this and state and cannot modify state directly, useState is a hook function for state operation exposed by react.
This function can receive a parameter, which is the default value of the variable. If it is not written, the variable is undefined by default.
useState returns an array. The first bit of the array is the variable name and the second bit is the function that changes the variable. If you check the source code, you will find that this function is a dispatch function (asynchronous), so you can directly view the variable to get the original value. If you want to view the variable value, use useEffect to listen.
The function that changes the variable has a parameter. When used, it directly puts the value type, not an expression, etc.

 const [number, setNumber] = useState(0) /* 0 Is the initial value */
 return (<div>
     <span>{ number }</span>
     <button onClick={ ()=> {
       setNumber(number+1) /* Writing method I */
       setNumber(number=>number + 1 ) /* Writing method 2 */
       console.log(number) /* The number here cannot be changed immediately  */
     } } >num++</button>
 </div>)

useEffect
Functional components also have no life cycle. Use effect instead of life cycle. At the same time, the value modified by useState can be obtained here to realize data interaction. useEffect is also called side effect. As the name suggests, it is executed after rendering is completed. In actual use, useEffect must fill in the second parameter to use, otherwise it may cause performance problems. For example, the data rendered twice are exactly the same.
The first parameter is the effect function, and the second parameter is the dependency, which is an array. If it is an empty array, useEffect does not depend on any value in props or state, so it will never need to be executed repeatedly. This hook will implement the function of componentDidMount life cycle function, that is, it will be triggered once when the page is loaded.
If it is not an empty array, add a variable in useState. Every time this variable changes, it will trigger useEffect, that is, componentDidUpdate, including componentDidMount.

  const [num, setNum] = useState(1)
  useEffect(() => {
    console.log('componentDidUpdate')
  }, [num])
  useEffect(() => {
    console.log('componentDidMount')
  }, [])
  return (
    <>
      <div>{num}</div>
      <button onClick={() => { setNum(num + 1) }}>click</button>
    </>
  )


Multiple useState values can be placed in the array, and each value change will trigger. In actual development, this dependency array only puts one variable. The second parameter generally does not use the reference type, because the comparison is shallow. If the pointer address of the reference type does not change, it cannot enter the useEffect.
In the first effect function parameter of useEffect, you can also return a function to indicate the side effects of unbinding. For example, there is a timer in the effect function, and the timer needs to be cleared when the component is destroyed. To unbind, you can return a function in the effect function, which is equivalent to the life cycle of componentWillUnmount. In use, when the dependency is re rendered, the debinding side effects will be performed first, and the side effects will be performed later, that is, the effect function.

  const [num, setNum] = useState(1)
  useEffect(() => {
    console.log('componentDidUpdate')
    return ()=>{
      console.log('componentWillUnmount')
    }
  }, [num])
  return (
    <>
      <div>{num}</div>
      <button onClick={() => { setNum(num + 1) }}>click</button>
    </>
  )

useMemo
Similar to useEffect, parameter is also a function and a dependency array. Its main function is to help avoid high overhead calculation during each rendering.
It recalculates the value only when a dependency changes. This process will be carried out during page rendering. The analogy life cycle is shouldComponentUpdate.
If no dependency array is provided, useMemo calculates a new value each time it renders. Do not perform rendering independent operations inside this function. Operations such as side effects belong to the applicable scope of useEffect, not useMemo.
useMemo will return the result of a memo function return() = > name. Use the defined variable to receive and use the defined variable.
Comparison with useEffect:
useMemo: controls the triggering / change of values / functions during rendering
useEffect: controls the trigger / change of value / function after rendering

// Product name list
const nameList = ['apple', 'peer', 'banana', 'lemon']

const example = (props) => {
  // Product name and price
  const [price, setPrice] = useState(0)
  const [name, setName] = useState('apple')

  function getProductName() {
    console.log('getProductName trigger')
    return name
  }
  
  // Respond only to price
  useEffect(() => {
    console.log('price effect trigger')
  }, [price])

  // Respond only to name
  useEffect(() => {
    console.log('name effect trigger')
    getProductName()
  }, [name])

  // Memoized getProductName function
  const memo_getProductName = useMemo(() => {
    console.log('name memo trigger')
    return () => name  // Returns a function
  }, [name])

  return (
    <Fragment>
      <p>{name}</p>
      <p>{price}</p>
      <p>ordinary name: {getProductName()}</p>
      <p>memo Standardized:{memo_getProductName()}</p>
      <button onClick={() => setPrice(price + 1)}>price+1</button>
      <button onClick={() => setName(nameList[Math.random() * nameList.length << 0])}>Modify name</button>
    </Fragment>
  )
}

useMemo can also wrap labels and subcomponents

/* The list wrapped with useMemo can be limited to updating the list only when the list changes, so as to avoid the recurrence of the selectList */
 {useMemo(() => (
      <div>{
          selectList.map((i, v) => (
              <span
                  className={style.listSpan}
                  key={v} >
                  {i.patentName} 
              </span>
          ))}
      </div>
), [selectList])}
/* Only when the list in props is changed, the sub component is rendered */
const  goodListChild = useMemo(()=> <GoodList list={ props.list } /> ,[ props.list ])

Keywords: react-hooks

Added by caaronbeasley on Thu, 06 Jan 2022 00:00:59 +0200