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

后端 未结 3 978
予麋鹿
予麋鹿 2021-02-15 01:58

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条回答
  •  梦毁少年i
    2021-02-15 02:52

    Here's an outline of the timings involved:

    • useEffect is called on the initial render and whenever any of the values it depends on change. In general, it fires after the rendering is completed. If you think of it in terms of a class-based component, equivalent would be componentDidMount method.
    • The function returned from within useEffect is invoked before the component is removed from the UI or is about to re-render (to avoid memory leaks). Previous effect is always cleaned up before performing the next effect. It's guaranteed to run before any new renders. Equivalent would be componentWillUnmount.

    Example

    Let's assume that there is a useEffect with few dependencies made of props (which are passed to our component) + a cleanup function. On the first render, the following would happen:

    • Once the component is mounted, code inside effect's body will run;
    • Cleanup function stays put, ready to run before the component re-renders / is removed from the screen.

    Now let's imagine something triggers a re-render. Since it's listed as something useEffect depends on, the effect will be re-executed as following:

    • Cleanup function executes after rendering is completed;
    • Right after that, code inside effect's body will run;
    • New cleanup function is created, again, ready to execute after the component re-renders / or before it's removed from the screen.

提交回复
热议问题