What is the expected return of `useEffect` used for?

天涯浪子 提交于 2021-02-18 06:27:21

问题


In the React documentation for hooks they say:

"This also allows you to handle out-of-order responses with a local variable inside the effect"

useEffect(() => {
    let ignore = false;
    async function fetchProduct() {
      const response = await fetch('http://myapi/product/' + productId);
      const json = await response.json();
      if (!ignore) setProduct(json);
    }

    fetchProduct();
    return () => { ignore = true };
  }, [productId]);

Demo app

Please help me understand this better by explaining:

  1. Why is the return a function? return () => { ignore = true };
  2. What is ignored used for in this example?

Thanks!


回答1:


Why is the return a function? return () => { ignore = true };

From the docs,

Why did we return a function from our effect? This is the optional cleanup mechanism for effects. Every effect may return a function that cleans up after it. This lets us keep the logic for adding and removing subscriptions close to each other. They’re part of the same effect!

And

When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time. We’ll discuss why this helps avoid bugs and how to opt out of this behavior in case it creates performance issues later below.

What is ignored used for in this example?

Initially in useEffect Hook ignore is set like, let ignore = false;. When fetchProduct function executes it checks for ignore is true and accordingly sets setProduct(json). This means we have state called product and setting the value in state using setProduct(json). This product in state is used to render details on page.

Note: As [productId] is passed as second argument to useEffect, fetchProduct function will only get executes when productId changes.

See optimizing performance by skipping effects.




回答2:


we use a boolean flag called ignore to let our data fetching logic know about the state (mounted/unmounted) of the component.If the component did unmount, the flag should be set to true which results in preventing to set the component state after the data fetching has been asynchronously resolved eventually. when component unmounted then return (second part of useEffect) is called. but in this case because of dependency [query] when query change, our component is re-rendered, so sideEffect is re-initialized. Run this code on your IDE then open Devtools in your browser like chrome and clear console then in input which the word react is written, add char 2 as fast as possible and then immediately remove char 2. check console to see what happened.




回答3:


//all imports
function mufunc(){
  useEffect(()=>{ 
    const a = addEventListner('mouse' , console.log('mouse moves') )  //it prints when 
                                                                      //mouse moves
    return ()=>{
      removeEventListner(a)  //whenever the component removes it will executes
    }
  } ,[])
}



回答4:


when component unmounted then return (second part of useEffect) is called. but in this case because of dependency [query] when query change, our component is re-rendered, so sideEffect is re-initialized. Run this code on your IDE then open Devtools in your browser like chrome and clear console then in input which the word react is written, add char 2 as fast as possible and then immediately remove char 2. check console to see what happened.



来源:https://stackoverflow.com/questions/56800694/what-is-the-expected-return-of-useeffect-used-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!