Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 132 ยท Hooks

useLayoutEffect, useId, useDebugValue and useInsertionEffect

Learn useLayoutEffect for measuring the DOM before paint, useId for accessible SSR-safe ids, useDebugValue for DevTools labels and useInsertionEffect for CSS-in-JS, plus a tour of other hooks.

Most React code needs useState, useEffect, useRef and a handful of others. But the hooks API has a few more specialised tools. Each exists to solve one narrow problem very well, and knowing they exist saves you from awkward workarounds: useLayoutEffect for fixing the layout before the browser paints, useId for unique ids that stay in sync between server and browser, useDebugValue for labelling custom hooks in React DevTools, and useInsertionEffect for the people who build CSS-in-JS libraries.

This lesson covers all four with runnable examples, and ends with a map of the rest of the hooks so that you know where to look next. It assumes you know useEffect and useRef.

The order things happen in

To understand useLayoutEffect you need the timeline of an update:

  1. Render: React calls your component and works out what the DOM should look like.
  2. Commit: React changes the DOM.
  3. (Browser calculates layout and paints the pixels to the screen.)
  4. Passive effects: your useEffect callbacks run.

A normal useEffect is deliberately run after the paint, so slow effects never delay what the user sees. That is the right default. The cost is that if an effect measures the DOM and then sets state, the user sees the first version for one frame, and then the corrected one: a visible flicker.

useLayoutEffect has the same signature as useEffect, but it runs in step 2 to 3: after React has changed the DOM, before the browser paints. If you set state inside it, React re-renders synchronously and the browser only ever paints the final result.

useLayoutEffect: measure, then adjust, before paint

Typical jobs: positioning a tooltip next to its target after measuring both, scrolling to a position, reading the height of an element to animate it, and any "render, measure, render again" situation.

This demo measures a box and shows its width. Both versions do the same thing; the only difference is the hook. The browser can only paint between JavaScript tasks, so a MutationObserver (its callback runs at the end of each task) tells us exactly which versions of the DOM the browser had a chance to paint.

useEffect versus useLayoutEffect before the first paint

Both paragraphs end up reading Measured width: 200px. The console shows the difference. The useEffect root logs two lines, could paint: "measuring..." and then could paint: "Measured width: 200px": the placeholder was in the DOM at the end of a task, so a real user may see it for a frame before the correction. The useLayoutEffect root logs only the final text. React ran the layout effect, saw the state update, re-rendered and committed again inside the same task, so the placeholder never existed at a point where the browser could paint it.

(Passing a hook as a prop is done here only to keep the demo short. Real components import the hook they need, because hooks must be called in a stable order.)

Rules for useLayoutEffect

  • It blocks painting. Slow code in a layout effect delays what the user sees. Keep it short and only measure and adjust.
  • Use useEffect unless you can see a flicker or need to read layout before paint. It is a corrective tool, not a default.
  • It has the same cleanup and dependency rules as useEffect (Cleanup, Subscriptions and Timers).
  • It does not run on the server. React warns about useLayoutEffect during server rendering in older versions; the standard pattern is to avoid it for anything that must exist on the server, or to use a mounted check. Frameworks give you helpers such as useIsomorphicLayoutEffect. See Server-Side Rendering and Hydration.
  • Reading layout forces the browser to calculate it (offsetWidth, getBoundingClientRect). Do several reads together, then writes, to avoid repeated forced layouts.

A common pattern is a tooltip that wants to sit above its anchor unless it would leave the screen. You render it once, measure it in useLayoutEffect, then update state with the final position. If you used useEffect, the tooltip would flash in the wrong place first.

The order of all three effect hooks

useInsertionEffect, which comes later in this lesson, completes the family. This demo logs the order they fire in on the first render:

Order of insertion, layout and passive effects

The logs appear in numbered order even though the hooks are declared in the opposite order in the source. Declaration order matters only among effects of the same kind.

useId: unique ids that match on server and client

Accessible forms connect a label to its input with matching htmlFor and id. Hard-coding an id (id="email") breaks as soon as the component appears twice on a page, because ids must be unique. Generating one with a counter or Math.random() breaks server rendering, since the server and the browser produce different values and React reports a hydration mismatch (Server-Side Rendering and Hydration).

useId() returns a string that is unique per component instance and the same on the server and in the browser.

Two instances, two different ids

Press "Check ids". The console reports that the ids are different and that clicking the second label focused the second input, so each label points to its own field. The exact text of the id is an implementation detail (React chooses its own format, which has changed between versions), so never parse it, use it in a CSS selector or rely on it as a stable value. Treat it as an opaque string.

Tips:

  • Call useId once per component and derive related ids by appending a suffix, as hintId above does.
  • Don't use useId for list keys. Keys should come from your data; useId is regenerated for new component instances and is meant for DOM attributes (id, htmlFor, aria-describedby, aria-labelledby, aria-controls).
  • It is safe in SSR and hydration, which Math.random() and global counters are not.
  • Pass an id through props when the caller needs control; use useId as the fallback for when none is given.

useDebugValue: labels for custom hooks in DevTools

React DevTools shows the hooks a component uses. For built-in hooks, it displays their values. For a custom hook, it shows the hook's name and the built-ins inside it. useDebugValue lets you attach a human-readable label to a custom hook so that the panel says something like OnlineStatus: "Online" instead of a raw boolean.

The hook does nothing visible in the page itself, so there is no output in the editor. The example runs but only demonstrates that it is harmless to call; the label appears in the DevTools panel of a real project.

A custom hook with a DevTools label

If formatting the label is expensive, pass a second argument, a formatting function: useDebugValue(date, (d) => d.toISOString()). React calls it only when DevTools is open and the hook is inspected. Use useDebugValue in shared library hooks, where other developers will inspect the hook. Adding it to every app-private hook is noise.

useInsertionEffect: for CSS-in-JS libraries

useInsertionEffect runs before React makes DOM changes (before layout effects can read the DOM). Its single purpose is for libraries that generate CSS at run time (CSS-in-JS) to inject <style> rules early enough that layout effects and refs read the correct styles. If the rule were inserted in a layout effect, reading layout in that same pass could see unstyled content and force a second expensive style recalculation.

The restrictions are strict:

  • You cannot update state inside it.
  • Refs are not attached yet.
  • It cannot see the DOM nodes of the current render.
  • It does not run on the server.
Injecting a style rule with useInsertionEffect

The layout effect reports padding-left = 10px, because the rule from the insertion effect was already in the document when the layout effect measured the element. Swap useInsertionEffect for useLayoutEffect and, since the two effects run in declaration order within a pass, the rule would also be there in this tiny case: the hook matters for large trees and for libraries that must guarantee the order. If you are not writing a styling library, you will never need this hook. Use a stylesheet, CSS Modules or Tailwind (Styling React Components). In React 19 you can also render <style> and <link rel="stylesheet" precedence="..."> elements directly in your components and let React hoist them.

A tour of the other hooks

You have now met most of what the react package exports. Here is a map, with where each is taught:

Hook One-line purpose Lesson
useState Local state State with useState
useReducer State with an update function you define useReducer and Reducers
useContext Read context Context
useRef Mutable box, DOM nodes useRef
useEffect Synchronize with outside systems useEffect
useEffectEvent Event-like logic inside effects useEffectEvent
useMemo, useCallback Cache values and functions useMemo and useCallback
useSyncExternalStore Subscribe to external stores External Stores
useTransition, useDeferredValue Keep the UI responsive during slow updates Transitions
useImperativeHandle Expose a limited API through a ref Refs and Imperative Handles
use Read a promise or context during render The use Hook and Suspense
useActionState, useFormStatus, useOptimistic Forms and actions in React 19 Form Actions

Everything on this page (useLayoutEffect, useId, useDebugValue, useInsertionEffect) is deliberately niche. If you reach for useLayoutEffect more than a few times in a project, check whether a CSS solution, a ref callback or restructuring the state would do the job.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does useLayoutEffect run compared with useEffect?

    Layout effects run synchronously after the commit and before paint, so state updates inside them are applied before the user sees anything. useEffect usually runs after paint.
  2. 2. A tooltip is measured in useEffect and then moved with state, and users see it jump. What is the usual fix?

    Measuring and adjusting before paint is the job of useLayoutEffect: the browser paints only the corrected result.
  3. 3. Why use useId instead of Math.random() to make an id for a label and input?

    Random values differ between server and browser renders, causing a mismatch. useId is designed to produce the same value in both.
  4. 4. What does useDebugValue change in the running page?

    useDebugValue only labels a custom hook in DevTools. It has no effect on rendering or output.
  5. 5. Who is useInsertionEffect intended for?

    It runs before DOM changes so styles can be injected early. You cannot set state in it and refs are not attached; application code should use stylesheets or the other effect hooks.

Summary

  • Updates run as render, commit, paint, then passive effects. useLayoutEffect runs after commit but before paint; useEffect runs after paint.
  • Use useLayoutEffect to measure the DOM and adjust synchronously when you would otherwise see a flicker; keep it short, since it blocks painting.
  • useId creates unique, SSR-safe ids for id, htmlFor and aria-* attributes; derive more ids from it with suffixes, and never use it for keys.
  • useDebugValue labels custom hooks in React DevTools and changes nothing on the page.
  • useInsertionEffect is for CSS-in-JS libraries; it runs before DOM reads, cannot set state, and application code rarely needs it.
  • The rest of the hooks each have their own lessons; reach for the specialised ones only when the simpler hooks cannot do the job.

Next: Custom Hooks