Inject generated styles
A CSS-in-JS library creates or updates a style element when generated rules change.
React 19+ · Hook
useInsertionEffect lets CSS-in-JS libraries insert styles before layout effects run. It is a specialized client-side hook, not a general replacement for useEffect or useLayoutEffect.
useInsertionEffect runs an effect setup when a component is added, before layout effects run, and repeats cleanup followed by setup when dependencies change. It is intended for CSS-in-JS libraries that must inject styles early; its cleanup runs when the component is removed.
useInsertionEffect(setup, dependencies?)| Name | Type | Description |
|---|---|---|
setup | function | Effect logic; it may optionally return a cleanup function. |
dependencies | array | Optional list of every reactive value referenced by setup, including props, state, and component-body declarations. |
undefined
import { useInsertionEffect } from 'react';
export function InjectRule({ rule }: { rule: string }) {
useInsertionEffect(() => {
const style = document.createElement('style');
style.textContent = rule;
document.head.appendChild(style);
return () => style.remove();
}, [rule]);
return null;
}This component adds a CSS rule before layout effects and removes the corresponding style element during cleanup.
A CSS-in-JS library creates or updates a style element when generated rules change.
A styling library removes a previously inserted rule when its owning component unmounts or its rule changes.
It is a specialized effect for CSS-in-JS libraries. React runs its setup before layout effects, allowing styles to be inserted before effects that may measure layout.
Follow-up: Why should ordinary components usually avoid it? Use useEffect or useLayoutEffect instead unless the code is implementing a CSS-in-JS library that needs this insertion point.
The setup function may return cleanup. On dependency changes, React runs cleanup with the old values and then setup with the new values; on unmount, it runs cleanup.
Follow-up: What must the dependency list contain? Every reactive value referenced by setup, including props, state, and variables or functions declared in the component body.
It returns undefined and runs only on the client. It cannot update state, refs are not attached yet, and DOM update timing should not be assumed.
Follow-up: How should server-rendered CSS be handled? The documentation only establishes that this effect does not run during server rendering, so CSS-in-JS code must not depend on this hook for server output.
useEffectuseLayoutEffect