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

前端 未结 4 1329
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 13:35

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\"

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-15 14:31

    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.

提交回复
热议问题