useLayoutEffect is a specialized effect Hook for work that must happen immediately after React updates the DOM but before the browser displays the update. It can prevent users from seeing an incorrect intermediate UI, such as a temporary 0 before a letter count appears. section 6.1.6
Preventing a visible intermediate value
Replace useEffect with useLayoutEffect when an effect updates state and the first rendered value would otherwise briefly appear on screen. The layout effect runs immediately, React applies the resulting state update, and the browser displays the corrected UI first. Keep useEffect as the default; useLayoutEffect is for specialized timing-sensitive cases. section 6.1.6
Treat useLayoutEffect as useEffect with different timing:
- Pass an effect function and a dependency array. section 6.1.6
- When a dependency changes, run the previous cleanup, then run the new effect. section 6.1.6
- Use it only when asynchronous useEffect timing produces a visible or otherwise incorrect result. section 6.1.6
Figure 6.13 The timing of useLayoutEffect versus useEffect. Note how the layout effect is run just after the DOM is updated, but before the browser has had a chance to lay out the elements using CSS. (Sorry for the crowded diagram!)
Compare the execution points of useLayoutEffect and useEffect: the layout effect runs after the DOM update but before the browser lays out elements with CSS. section 6.1.6
