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
The explanation provided by @Powell Ye is good however there a bit of erroneous information specifically when speaking about re-renders (e.g. when props change)
consider some simple component with the following
useEffect( () => {
console.log('Effect is applied')
//some logic
return () => {
console.log('cleaning up')
//cleanup logic
}
})
return (<>
{console.log('rendering...')}
</>)
say the props passed in changes you might think it goes as such
However, the following actually occurs
That is, the clean up function runs AFTER the new render/painting but BEFORE the 'new' effects are applied, the docs can be a bit ambigious about this
the previous effect is cleaned up before executing the next effect
This is done for performance reasons => so that rendering is not delayed ( it can be frustrating at times for me too )
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).
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.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
.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:
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: