Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.8 — useLayoutEffect and useInsertionEffect
React · Example 3 of 3 React 18+

useInsertionEffect: styles in place before anyone measures

Each Badge asks for its style; the first insertion adds the <style> tag (the Set prevents duplicates). Because all insertion effects run before any layout effect, both measurements see the 120px width from the injected CSS.

useLayoutEffect runs after React updates the DOM but before the browser paints, so you can measure elements and fix the layout without a visible flicker, at the cost of blocking the paint; useInsertionEffect runs even earlier and exists for CSS-in-JS libraries to insert styles.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a component that renders a <textarea> and, in a layout effect depending on value, sets its height to its scrollHeight so it grows with the text.

02

Which hook would you use to log a page view, and which to scroll a chat list to the bottom before the new message is shown? Why?

Explain it without notes

01

How does useLayoutEffect differ from useEffect, and when would you choose it?

02

Explain how a tooltip can measure itself and reposition without the user seeing a jump.

03

What happens to useLayoutEffect during server rendering in React 19?

04

What is useInsertionEffect for, and why does it run before layout effects?

useInsertionEffect: styles in place before anyone measures React 18+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

insertion effect: added <style> for .badge-xl
layout effect: badge width is 120
layout effect: badge width is 120