When is the cleanup function triggered when using useEffect hook with dependencies?

后端 未结 3 1990
Happy的楠姐
Happy的楠姐 2021-02-15 01:59

I\'m using a useEffect to show a UI Loading... but only after 250ms. It works ... but I really don\'t understand why and specially how and when useEffect invokes the returned fu

3条回答
  •  無奈伤痛
    2021-02-15 02:57

    As per the react documentation,

    Cleaning up an effect

    The clean-up function runs before the component is removed from the UI to prevent memory leaks. Additionally, if a component renders multiple times (as they typically do), the previous effect is cleaned up before executing the next effect.

    Timing of effects

    React will always flush a previous render’s effects before starting a new update.

    As per my understanding from both the quotes, cleanup runs after the effect is applied and before the component is unmounted (removed from UI).

提交回复
热议问题