UseEffect is arguably the most commonly used function in the React Hooks API. It takes two arguments:

  1. Side effect callback function
  2. Dependency array
function useEffect(effect: EffectCallback, deps? : DependencyList) :void;
Copy the code

Where, the number of times the callback function is executed completely depends on the dependency array, and the following three situations occur:

Dependencies are empty arrays

If the dependency is an empty array, then the callback is executed only once on the first rendering, just as componentDidMount does:

useEffect(() = > {
  // The code here is executed only once on the first rendering
}, [])
Copy the code

Again, recall the componentDidMount method, which is called immediately after the component is mounted (inserted into the DOM tree).

No dependencies

If the dependency is not specified, i.e. the second argument is undefined, the callback is executed on the first rendering and every re-rendering, just as componentDidMount plus componentDidUpdate.

useEffect(() = > {
  // The code here is executed every time
})
Copy the code

A review of the componentDidUpdate method:

componentDidUpdate(prevProps, prevState, snapshot)
Copy the code

It will be called immediately after the update. This method is not performed for the first rendering.

Dependencies are arrays of variables

If one or more dependencies are specified, i.e. [variable1, variable2], the callback is executed on the first rendering and when the dependency changes, PrevState. VariableN = this.state. VariableN = prevState. VariableN = prevState.

useEffect(() = > {
  // The code here is executed on the first rendering and on re-rendering due to variable1 or variable2 changes
}, [variable1, variable2])
Copy the code