You've used useEffect a thousand times. But did you know it runs after the browser paints? That means if you're measuring the DOM to position an element, users will see a flicker โ the element renders at the wrong position, then snaps into place. useLayoutEffect fixes that by running before paint. This challenge proves it with a tooltip.
๐งฉ Overview
A tooltip component needs to center itself by measuring its own width. The starter uses useEffect, causing a visible flicker โ the tooltip appears uncentered for a moment before snapping to the middle. Replace it with useLayoutEffect and the measurement happens before the browser paints, giving you a perfect first frame.
๐ https://www.reactchallenges.com/challenges/use-effect-vs-use-layout-effect
โ Requirements
- Replace
useEffectwithuseLayoutEffectin the TooltipContent component so the tooltip is centered before the browser paints, avoiding the flicker.
๐ก Notes
-
useLayoutEffectruns before paint โ use it for DOM measurements. -
useEffectruns after paint โ use it for logging, subscriptions, and side effects that don't affect layout. - Pro tip: if the flicker is too fast to see, enable CPU throttling (4x or 6x) in DevTools โ Performance tab.
๐งช Tests
- Uses useLayoutEffect for the DOM measurement
This is one of those hooks that doesn't come up often โ but when it does, knowing the difference between useEffect and useLayoutEffect is the difference between a polished UI and a janky one. A single line change, a world of difference.
Top comments (0)