useInsertionEffect
In one line
useInsertionEffect fires before any DOM mutation — use it for CSS-in-JS style injection, not general logic.
In simple words
useInsertionEffect (React 18) is a variant of useEffect that fires synchronously before any DOM mutations. It's designed specifically for CSS-in-JS libraries (styled-components, emotion) that need to inject <style> tags before the browser paints.
It runs before useLayoutEffect and before the DOM is updated. You should NOT use it for general-purpose logic — only for style injection. It doesn't have access to refs because the DOM hasn't been updated yet.
Most developers will never use this directly — it's for library authors. If you're building a CSS-in-JS library, use this to inject styles before paint to avoid flash of unstyled content.
Example
import { useInsertionEffect } from "react";
function useStyledComponent(styles) {
useInsertionEffect(() => {
// Inject <style> before DOM mutation
const tag = document.createElement("style");
tag.textContent = styles;
document.head.appendChild(tag);
return () => document.head.removeChild(tag);
}, [styles]);
}
function Button({ children }) {
useStyledComponent(`
.btn { background: blue; color: white; padding: 8px 16px; }
`);
return <button className="btn">{children}</button>;
}useInsertionEffect injects styles before DOM mutations, preventing flash of unstyled content. Only for CSS-in-JS libraries.
Common confusions
Confused with: useLayoutEffect
The difference: useLayoutEffect runs after DOM mutations but before paint — it can read layout (measurements). useInsertionEffect runs before DOM mutations — it cannot read layout. Use useInsertionEffect for style injection, useLayoutEffect for DOM measurements.
Related terms
Related Resources
Related Lessons
- React 18 Features
useInsertionEffect.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.