The update 2021.7.11

State Hooks

Example:

import { useState }  from 'react'

const Increase = () = > {
  const [count, increase] = useState(0)
  return <div>
    <button onClick={() = > increase(count + 1) }>increase</button>
    <span>{count}</span>
  </div>
}

export default Increase
Copy the code

Increase is a method that accepts arguments to change the value of count. UseState can set the initial value of count with the argument. It can be a primitive type or a function that returns a value… UseState (() => 0) useState can also define arrays or objects:

const [obj, increase] = useState({ a: 1 })
Copy the code

Effect Hooks

Example:

import { useState, useEffect }  from 'react'

const Increase = () = > {
  const [count, increase] = useState(0)

  useEffect(() = > {
    console.log(count)
  })

  return <div>
    <button onClick={() = > increase(count + 1) }>increase</button>
    <span>{count}</span>
  </div>
}

export default Increase
Copy the code

UseEffect Hook can be seen as a combination of componentDidMount, componentDidUpdate, and componentWillUnmount. UseEffect Hook is executed after every DOM rendering. React ensures that the DOM is updated every time effect is run. The first effect argument returns a function that removes side effects, such as:

  // After component destruction, the related event listener should be destroyed to prevent memory leakage, etc
  const handle = () = > {}
  useEffect(() = > {
    document.addEventListener('click', handle)
    return () = > {
      document.addEventListener('click', handle)
    }
  })
Copy the code

UseEffect takes the second parameter. What is the effect of this parameter? If count is 5 and our component rerenders with count still equal to 5, React will compare the previous render [5] to the subsequent render [5] (per value). If they are equal, the effect is skipped, otherwise it is executed. It looks like a watch for VUe2, but vue3 also implements this effect (manual funny)

  useEffect(() = > {
    console.log(count)
  }, [count])
Copy the code