This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

In this article we will learn about the useEffect, which is a new React Hook. We will learn about the useEffect of the React Hook

A,useEffectAnalyze the

1. Let’s have a look at it firsteffect(Side effects), which are not used to occur inData viewLogic in the transformation process, for exampleData request,Accessing DOM elements,Caching operations,Bind/cancel event listening,To subscribe to,Set timerAnd so on theData viewOperations in logic are side effects

2,useEffectFeatures:

UseEffect provides functional components with the ability to manipulate side effects (it is not allowed to manipulate side effects in functional components because it may break data interface consistency). UseEffect integrates the three life cycles of React componentDidMount, componentDidUpdate and componentWillUnmount. Functional components can use the useEffect hook to perform the same logic for all three life cycles in a class component

React Hooks are repeatable and independent of each other, so when writing logic we can bind a useEffect hook to each side effect operation so that we do not need to write multiple side effects in a single lifecycle

3,useEffectThe use of

  • UseEffect can take two arguments. The first argument is a function for side effects. The second argument is an array of elements that are a condition for the side effect operation to be executed when the state of the element in the array is updated

  • Basic use: Use useEffect: Pass the function as an argument to the useEffect hook function. The logic inside this function is the side effect to be done

    function Title() {
        const [title, setTitle] = useState("Jue Jin");
        useEffect(() = >{
            document.title = `Welcome to ${title}! `; })}Copy the code
  • We can also specify state variables that trigger side effects with constraints:

    function Title() {
        const [title, setTitle] = useState("Jue Jin");
        const [number, setNumber] = useState(1);
        // Side effects are performed only after the title changes
        useEffect(() = >{
            document.title = `Welcome to ${title}`;
        },[title])
        return (
            <div>
                <h1>{number}</h1>
                <button onClick={()= >{ setNumber(number=>number+1) }}> + 1 </button>
            </div>)}Copy the code
  • The useEffect binding will process the side effect logic once after each rendering. To clear the side effect, there are two ways: pass a new function to useEffect, or pass an empty array to the second argument of useEffect. When the second argument is passed in an empty array, the side effect does not depend on an update of a state, and is called only in the component’s mount process (that is, only once), not during the update phase

    // Return a new function
    //useEffect calls the last returned function before executing the side effect
    useEffect(() = >{
        if(! destroy){document.title = `Welcome to ${title}`;
        }else{
            return () = >{
                console.log("useEffect destroyed"); }}})// The second argument is passed an empty array
    useEffect(() = >{
        document.title = `Welcome to ${title}`; }, [])Copy the code
  • We can also use multiple Useeffects to separate out multiple side effects operations without the hassle of stacking them in the same lifecycle as class components

4. Precautions

UseEffect is called every time a view is rendered (first render + update render). UseEffect is called every time a view is rendered.

In addition, componentDidMount and componentDidUpdate in the code is synchronous execution, will block the browser view update, and useEffect in the side effect is asynchronous, will not block the browser view update, can meet the basic side effect arrangement requirements

Second,useLayoutEffect

The useEffect is asynchronous and does not block the browser from updating the view, but what if I want to do it synchronously? To do this, use useLayoutEffect (although useEffect is usually sufficient). Here is a flow chart for browser rendering:

Regardless of the mechanism, the use method is no different from useEffect, where:

  1. useEffectSide effects are called after the browser has rendered
  2. useLayoutEffectWill be inLayout(DOMwithCSSOMAfter merging, arranging),Painting(Draw) before performing side effects
  3. useLayoutEffectWill be inDOMCall side effects synchronously after update
  4. Special usage: We can use ituseLayoutEffectIn order to getDOMElement information, after doing the corresponding processing, trigger the render synchronously.

Three, reference articles:

React Hooks + Project Combat

React Hooks in 30 Minutes