Make React useEffect hook not run on initial render
This custom hook, useUpdateEffect
will come to the rescue for effects that skip the initial render. It uses useRef
to distinguish between the initial mount and further updates.
Using useRef for tracking initial render
The useRef
hook creates a mutable object reference, which is excellent for tracking the initial render:
This means useRef
will store the first render value and won't trigger a re-render, which makes it mostly unregister in this family. It just sits alone in the corner and tracks things without getting in the way.
Synchronization layout effects
useLayoutEffect
lets your effect run synchronously after all DOM mutations. This brings the same family traits as componentDidUpdate
, ensuring effects are synchronized with UI updates.
Just remember, with great power, comes great responsibility๐. Make sure your effects don't block the UI thread and get someone mad at you.
Mastering useEffect like a pro!
Keeping functions cool with unmounting
Always remember to stay cool๐ง and clean up when your effect has done its job - Unmount your functions within effects:
Persistence is key
If you have data you need to persist across renders, useRef
got your back:
Was this article helpful?