useInsertionEffect Hook
useInsertionEffect Hook — Optimization of CSS-in-JS libraries
useInsertionEffect is a special React hook that appeared in React 18. It's designed for CSS-in-JS libraries (e.g., styled-components, Emotion, JSS, etc.) to ensure that CSS styles are injected into the DOM at the right time — before rendering.
This is a performance hook that allows React to prevent "unstyled flash" — when a component appears on screen without its CSS and only gets styled a second later.
React's rendering process can be divided into three phases:
useInsertionEffect works exactly at the beginning of the commit phase — before React writes DOM changes, meaning before useLayoutEffect.
Here's how the hook is used in React:
import React, { useInsertionEffect } from 'react';
export default function StyledBox() {
useInsertionEffect(() => {
const style = document.createElement('style');
style.innerHTML = `
.styled-box {
background: linear-gradient(45deg, #2196f3, #21cbf3);
color: white;
padding: 20px;
border-radius: 8px;
transition: all 0.3s ease;
}
.styled-box:hover {
transform: scale(1.05);
}
`;
document.head.appendChild(style);
return () => {
document.head.removeChild(style);
};
}, []);
return <div className="styled-box">Beautiful styled box 💎</div>;
}
In this example, CSS is injected into the DOM before rendering, meaning when the component renders, it's already styled without visible flicker.
Let's see what difference it makes if we do the same with `useEffect` instead of `useInsertionEffect`:
useEffect(() => {
const style = document.createElement('style');
style.innerHTML = '.red { color: red; }';
document.head.appendChild(style);
}, []);
In this case, the style will be added only after React renders the component. This means the user might see unstyled, unformatted UI for half a second ("unstyled flash").
useInsertionEffect solves exactly this problem — injecting CSS before browser paint.
This hook is not intended for regular programmers. If you're not writing a CSS-in-JS library or framework, you'll likely never need to use it.
This hook doesn't return any value. It only performs a "side effect" — helping React inject CSS at the right time.
Write a component that: