useEffect
The useEffect
hook serves a the primary way for handling side effects in a Melody component.
It allows you to execute code when,
it is mounted
it is updated
it is unmounted (removed)
Execute a side effect when needed
useEffect(sideEffectFunction, cacheKeyProperties[])
The most common form of useEffect
accepts a function, the side effect you want to execute, and an array of variables it depends on. Those cacheKeyProperties
are used to determine whether to execute the side effect again or not.
Execute a side effect on mount and unmount
useEffect(sideEffectFunction, [])
When given an empty array the side effect will never be evaluated again, as the cache key never changes. This gives a chance to build a side effect that executes when the component mounts and unmounts.
Use a side effect on mount, every render and unmount
useEffect(sideEffectFunction)
You can also omit the cacheKeyProperties
array entirely if you want to create a side effect that executed every time the component is rendered.
While technically feasible you most likely won't need this variant. It is a performance disaster waiting to happen.
We strongly advise that if you do really need it, you accompany it with some documentation on why you decided to go that route to help your colleagues avoid introducing issues later on.
Last updated
Was this helpful?