InterviewHubPRO
Section Overview
Q311

Question 311 of 445

Part 9: React Hooks Deep Dive (262 - 316)

70%
React & Modern Frontend (445 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

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

js
useInsertionEffect(() => {
// Insert styles here
return () => {
  // Cleanup
};
}, [dependencies]);

Execution Order

markdown
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

jsx
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.