javascript / expert
Snippet
Visual Synchronization with useLayoutEffect and RAF
useLayoutEffect fires synchronously after all DOM mutations but before the browser has a chance to paint. Combined with requestAnimationFrame, it allows for seamless layout adjustments and animations that avoid visual flickering, as the browser won't render the 'broken' state before your corrections are applied.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
useLayoutEffect(() => {const element = ref.current;let frameId;const adjustPosition = () => {const rect = element.getBoundingClientRect();if (rect.top < 0) {element.style.transform = `translateY(${Math.abs(rect.top)}px)`;}frameId = requestAnimationFrame(adjustPosition);};frameId = requestAnimationFrame(adjustPosition);return () => cancelAnimationFrame(frameId);}, [dependency]);
react
Breakdown
1
useLayoutEffect
Used here to measure the DOM and apply styles before the user sees the first frame.
2
requestAnimationFrame
Schedules the function to run before the next paint, ensuring smooth visual updates.
3
cancelAnimationFrame(frameId)
Critical cleanup to prevent memory leaks and unexpected behavior when the component updates.