React Reference ยท Effect and Ref Hooks
React useInsertionEffect hook
Reference for React useInsertionEffect: the hook for CSS-in-JS libraries to insert style rules before layout effects read the DOM, with timing and restrictions.
useInsertionEffect is a special-purpose hook for CSS-in-JS library authors. It runs after React has computed the DOM changes but before any layout effect reads the layout. That makes it the right moment to insert <style> rules, so that measurements taken in useLayoutEffect already see the final styles.
If you are not writing a styling library, you almost never need it. Use CSS files, CSS modules, or a library that already handles this.
useInsertionEffect(() => { // insert a <style> rule here return () => { /* remove it */ }; }, [rule]);
Try it
Syntax
useInsertionEffect(setup, dependencies?)
function useInsertionEffect( setup: () => void | (() => void), dependencies?: ReadonlyArray<unknown> ): void;
| Name | Description |
|---|---|
setup |
Inserts styles. May return a cleanup. |
dependencies |
Same rules as for useEffect. |
Returns: nothing.
Restrictions: inside an insertion effect you cannot read refs (they are not attached yet) and you cannot schedule state updates; it does not run on the server.
Usage notes
- Order within a commit: insertion effects first (DOM is mutated but refs are not attached), then layout effects, then passive effects.
- Why it exists: if styles were injected in a layout effect or normal effect, the browser could have already computed layout with old styles, causing extra recalculation or flicker.
- Server rendering: a library must collect its rules separately and write them into the HTML itself, because this hook never runs on the server.
- Do not set state or read the DOM here. Keep it to inserting and removing rules.
- Avoid in app code. Components should not inject global style tags themselves; a shared library should own that job.
- Cleanup matters: remove or reference-count rules so dynamic styles do not pile up.