Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hook is a new feature in React 16.8. It lets you use state and other React features without having to write a class.

I used to use Vue in my previous job, but recently I changed my job and the company used React, so I began to learn React. Now that React Hook has been launched, of course, I will use the new one instead of the old one.

useState

    import React, { useState } from 'react'
    
    const Counter = props= > {
      // Declare a state variable count with an initial value of 0
      const [count, setCount] = useState(0)
      // declare a state variable num with an initial value of props. Num flipped
      const [num, setNum] = useState(() = > {
          let { num } = props
          return parseInt((num + ' ').split(' ').reverse().join(' '))})return (
        <div>
          <p> count: {count} </p>
          <p> num: {num} </p>{/* Call setCount to change the value of count */<button onClick={()= > setCount(count + 1)}> add Count </button>
          <button onClick={()= > setNum(num + 1)}> add Num </button>
        </div>)}export default Counter
Copy the code

Each Hook is in useXXX format. UseState is a Hook that adds some internal state to the component. React retains this state when rendering repeatedly. UseState takes an argument as an initial value, returns the current state in array form and the function that updates it. When the initial value needs to be computed, it passes in a function that returns the initial value, and this function is called only during the initial render.

useEffect

    import React, { useState, useEffect } from 'react'
    
    const Counter = props= > {
      
      const [count, setCount] = useState(0)
      const [num, setNum] = useState(0)
      useEffect(() = > {
          console.log('Initialized, equal to componentDidMount')
          return () = > console.log('Destroyed, quite componentDidUnmount')
      })
      useEffect(() = > {
          console.log('count' changes:${count}`)
      }, [count])
      return (
        <div>
          <p> count: {count} </p>
          <p> num: {num} </p>
          <button onClick={()= > setCount(count + 1)}> add Count </button>
          <button onClick={()= > setNum(num + 1)}> add Num </button>
        </div>)}export default Counter
Copy the code

UseState implements the state of the class, while useEffect implements the lifecycle of the class. UseEffect can take two arguments, the first a function and the second an array. When no second argument is passed or an empty array is passed, the first function is executed at componentDidMount and every time the component is rerendered. The effect is equivalent to that of componentDidUpdate. This function can also return a function that is executed at componentDestruction. Equivalent to componentWillUnmount.

Some operating component to render every time we do not want to, just want to when there is a change in some specific values to perform, this is the second parameter will be used, will depend on the variables of fill in the second parameter in the array, the component will be in the initialization rendering and the array of values to perform the first function when there is a change. UseEffect, like useState, can be used multiple times in a component. You can split the different logic into different Useeffects.

useCallback

    const [num, setNum] = useState(0)
    const printNum = useCallback(() = > {
        console.log(` num:${num}`)
    }, [num])
Copy the code

UseCallback also takes two arguments, a function and an array of dependencies, and returns a cached first function that is updated only when the dependency changes, and not if there are no dependencies. Normally defined functions that are updated and reassigned when the component is re-rendered will cause the child component to render unnecessarily if this function is passed. This Hook solves this unnecessary re-rendering.

useMemo

    const [num, setNum] = useState(0)
    const doubleNum = useCallback(() = > num * 2, [num])
Copy the code

UseMemo receives the same parameters as useCallback, but useMemo caches the return value of the first function, which is recalculated when the dependency changes. UseMemo can achieve the effect of useCallback by returning a function from the first function, but this is not recommended because both hooks are defined as a cached function and a cached value.

The above is my first experience of React Hook. It’s a good experience. Hope to continue!