React useEffect is one of the most difficult hooks to understand. When you use it, you need to understand its execution. What happened to the update

Let’s see what the arguments to useEffect are, why do we write this argument, and what’s wrong with not writing it?

   useEffect(() = > {
       return () = >{}; } []);Copy the code
  • Up here is auseEffectThe complete way to write the function, let’s analyze ituseEffect, includinguseEffect(() => {})In theArrow functionMy personal understanding is yesuseEffecttheeffectThe delta function, which is deltaSide effect function.effectIn the functionreturnAt the back of theArrow functionPersonally understood asuseEffectFunction of theReturn the functionThis function is executed when the current component is unloadeduseEffect(() => { return () => {}; } []);The last argument in[], it isuseEffectFunction, which represents the currentuseEffectThe dependent data is changed after execution, as shown in the figure below
function Test() {
    
    useEffect(() = > {
        console.log('useEffect1')
    })

    useEffect(() = > {
        console.log('useEffect2')
        return () = > {
            console.log('useEffect2 uninstalled ')
        }
    })

    useEffect(() = > {
        console.log('useEffect3')
        return () = > {
            console.log('useEffect3 uninstalled ')}}, [])return (
        <div>Test</div>)}export default Test;
Copy the code

The results are posted below

Now let’s add a little bit of proof to this understanding

import {useEffect} from "react";


function Test() {
    const [n ,setN] = useState(0);


    useEffect(() = > {
            console.log('useEffect1')
    })

    useEffect(() = > {
        console.log('useEffect2 n after the change. ')
    },[n])

    useEffect(() = > {
        console.log('useEffect3')
        return () = > {
            console.log('useEffect3 component uninstalled ')}}, [])return (
          <div>
            <div>n: {n}</div>
            <button onClick={()= > setN(n+1)}>n+1</button>
          </div>)}export default Test;
Copy the code
function App() {

    const [isShow, setIsShow] = useState(true);
    return (
        <div>
            {isShow && <Test></Test>}
            <button onClick={()= >SetIsShow (false)} > hide the Test</button>
        </div>
    )
}

ReactDOM.render(<App />.document.getElementById(('root')))
Copy the code
Take a look at the results of this code

  • During component initialization, threeeffectAll functions will be executed, so that’s fine, but let’s see what happens when the data in the component changes

As you can see, let’s clickN + 1 buttonLater,nHas changed the value ofuseEffect1useEffect2It was executed, anduseEffect3It’s not implemented. Why is that?

The difference between useEffect1 and useEffect2 is that the dependencies in useEffect1 are not set. In this case, all updates to useEffect1 are executed when the component is initialized. UseEffect2 sets the dependency to n, which is executed when n changes and is initialized. Let’s see why useEffect3 is executed after the page is initialized and there are other changes in the component. Because the dependency on useEffect3 is set to [] not to depend on any data, which is what happens when the page is initialized. Ok, so we’ve made it clear that useEffect1 and useEffect2 are executed, useEffect3 is not executed, Let’s see what happens when I click hide the Test component

seeuseEffect3Return the functionIt’s being executed, so it’s going to beclassThe component’sUnloading phase

In the end, I put my own summary of useEffect function, if there are mistakes, thank you for correcting

useEffect(()=> { return ()=> {}},[])

  • Parameter 1 effect => Send a request to modify the data…
  • Parameter 2 the effect function depends on the parameter to determine how effect is updated
  • Return function ==> Do something when the component is to be unloaded

Enforcement mechanism

  • During the mount phase => 1 Execute useEffect and save effect to a queue
  • If the mount is complete => Execute the effect function queue

Update the stage

  • The new useEffect function is executed, and the effect function is queued for execution
  • Execute the return function queue, and observe whether the return function book has dependent parameters, have dependent parameters, trace whether the dependent parameters change, change the execution, no change is not executed
  • Execute the effect function queue, observe whether the effect function has dependent parameters, if there are dependent parameters, track whether the dependent parameters change, change the execution, no change is not executed

Unloading phase

  • 1 Execute the return function queue