Open In App

React useInsertionEffect Hook

Last Updated : 16 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

React useInsertionEffect Hook is used in React 18 to insert elements like dynamic styles, into the DOM before the layout effects are fired. This hook is mainly created to run on the client side, which makes it perfect for situations where the pre-layout element insertion is important.

Syntax:

useInsertionEffect(setup, dependencies?)

What is useInsertionEffect Hook in React?

The useInsertionEffect hook in React 18 is designed specifically for CSS-in-JS library authors, providing a synchronous execution before any layout effects. It performs the insertion of global DOM nodes, such as <style> or SVG <defs>, important for managing dynamic styles in CSS libraries. Unlike useLayoutEffect, useInsertionEffect avoids unnecessary layout computations and assures that styles are inserted at the right time during React’s rendering process. It is not recommended for general use and has limitations, such as the inability to access refs or schedule updates, making it suitable only for specific scenarios like dynamic style injection.

Syntax:

useInsertionEffect(()=>{
// inserting dynamic styles before layout effects fire
return()=>{
// clean function
}
}, [])

Steps to Create React Application:

Step 1: Create a react project folder, open the terminal, and write the following command.

npm create-react-app project
cd project

Step 2: Install the required dependencies.

npm i react-bootstrap bootstrap

Project Structure:

Project Dependencies:

  "dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.2",
"react": "^18.2.0",
"react-bootstrap": "^2.9.2",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example 1: In the below example, we have used the userInsertionEffect hook, where a dynamic color style is applied to the text element with the class as “dynamic-element”. The color of the text changes from green to red on each button click, which demonstrates the hook’s task to insert and update styles before layout effects are fired.

Javascript




//App.js
 
import React, { useState } from 'react';
import { useInsertionEffect } from 'react';
function App() {
    const [dyna_color, set_Dyna_Color] = useState('green');
    const dStyle = `
    .dynamic-element {
      color: ${dyna_color};
      transition: color 0.5s ease;
    }
  `;
    useInsertionEffect(() => {
        const styleEle = document.createElement('style');
        styleEle.innerHTML = dStyle;
        document.head.appendChild(styleEle);
        return () => {
            document.head.removeChild(styleEle);
        };
    }, [dyna_color]);
    const btnFn = () => {
        set_Dyna_Color('red');
    };
    return (
        <div className="dynamic-element">
            <h1>Hello, GeeksforGeeks!</h1>
            <h3>useInsertionEffect Hook - Example 1</h3>
            <button onClick={btnFn}>Change Color</button>
        </div>
    );
}
export default App;


Step to Run the Application: Run the application using the following command from the root directory of the project.

npm start

Output:

Output1

Example 2: In the below example, we are using the React useInsertionEffect Hook to dynamically inject and update the styles for the button. The theme state and updating the button’s appearance based on button clicks are done using the hook.

Javascript




// App.js
 
import React, { useState } from 'react';
import { useInsertionEffect } from 'react';
function App() {
    const [btn_Theme, set_btn_Theme] = useState('dark');
    const [count, set_Count] = useState(0);
    useInsertionEffect(() => {
        const rule = styleRuleFn(btn_Theme);
        document.head.appendChild(rule);
        return () => document.head.removeChild(rule);
    }, [btn_Theme, count]);
    const btnFn = () => {
        set_Count((prevCounter) => prevCounter + 1);
        set_btn_Theme(btn_Theme === 'dark' ? 'light' : 'dark');
    };
    return (
        <div>
            <h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
            <h3>useInsertionEffect Hook - Example 2</h3>
            <button onClick={btnFn}>
                {btn_Theme === 'dark' ? 'Light Mode' : 'Dark Mode'} - Click Count: {count}
            </button>
        </div>
    );
}
const styleRuleFn = (theme) => {
    const tag = document.createElement('style');
    tag.innerHTML = `
    button {
      color: ${theme === 'dark' ? 'white' : 'black'};
      background-color: ${theme === 'dark' ? 'black' : 'white'};
      transition: color 0.5s, background-color 0.5s;
    }
  `;
    return tag;
};
export default App;


Step to Run the Application: Run the application using the following command from the root directory of the project.

npm start

Output:

Output2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads