React question detail
What is the useInsertionEffect hook?
The useInsertionEffect hook is designed for CSS-in-JS library authors to inject styles into the DOM before any layout effects run. It fires synchronously before DOM mutations.
Syntax
useInsertionEffect(() => {
// Insert styles here
return () => {
// Cleanup
};
}, [dependencies]);
Execution Order
1. useInsertionEffect → Inject styles
2. DOM mutations → React updates DOM
3. useLayoutEffect → Read layout, synchronously re-render if needed
4. Browser paint → User sees the result
5. useEffect → Side effects run
Example: Dynamic Style Injection
import { useInsertionEffect } from 'react';
let isInserted = new Set();
function useCSS(rule) {
useInsertionEffect(() => {
if (!isInserted.has(rule)) {
isInserted.add(rule);
const style = document.createElement('style');
style.textContent = rule;
document.head.appendChild(style);
}
}, [rule]);
}
function Button() {
useCSS('.dynamic-btn { background: blue; color: white; }');
return <button className="dynamic-btn">Click me</button>;
}
Note: This hook is not intended for application code. It's specifically for CSS-in-JS libraries like styled-components or Emotion to prevent style flickering.