useEffect
An effect is a name for a function that is tied to a specific component and that runs on specific events or amidst certain conditions.
An effect runs after the component has rendered and been painted on screen, so that it never delays such paint. If the effect intends to mutate some data drawn on screen, such data will first be painted with an initial value or be hidden with a loader or a skeleton.
effect
we call useEffect
to register an effect.
run effect on some events and on certain conditions.
React runs the effect at least once, unconditionally: after the component's first paint.
Then, it runs the effect again if such effect has indicated its will for re-runs. The effect may request:
- to be re-run on every render
- to be re-run whenever one or more specific variables change in their values, usually because the effect makes use of that value to produce some relevant side-effects.
clean up
React runs the clean up function when the component unmounts.
synopsis
useEffect(effect, dependencies)
effect function
the effect function may not use top level await, because it may not be an async function.
function myEffect() {
/* effect content */
return /* clean up content */
}
dependencies
useEffect(effect, []) // once
useEffect(effect, [x]) // once, then when x changes
useEffect(effect) // on every render