React useInsertionEffect Hook
Last Updated :
02 Aug, 2024
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:
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:
Similar Reads
ReactJS useEffect Hook
The useEffect hook is one of the most commonly used hooks in ReactJS used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.What is
4 min read
ReactJS useSelect hook
The useSelect is a custom hook provided by the Rooks package for React. It is a list selection hook that helps select values from a list. Arguments: list: It is of the type array which describes the list of items for the selection. The default value is undefined.initialIndex -It is of the type numbe
2 min read
ReactJS useLayoutEffect Hook
The React JS useLayoutEffect works similarly to useEffect but rather works asynchronously like the useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the
2 min read
ReactJS useTransition Hook
When building interactive user interfaces, performance is a crucial aspect to consider. One way to improve the performance of a React application is by using the useTransition hook. This hook allows you to specify some state updates as not as important, by separating the animation-related state chan
5 min read
React useState Hook
The useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import
5 min read
ReactJS useRef Hook
The useRef Hook is a built-in React Hook that returns a mutable reference object (ref) that persists across renders. Unlike state variables, updating a ref does not trigger a component re-render.Syntaxconst refContainer = useRef(initialValue);useRef returns an object { current: initialValue }.The .c
3 min read
ReactJS useContext Hook
In React Applications, sometimes managing state across deeply nested components can become very difficult. The useContext hook offers a simple and efficient solution to share state between components without the need for prop drilling.What is useContext Hook?The useContext hook in React allows compo
5 min read
React useSyncExternalStore Hook
State management is a critical aspect of React applications, and often, developers need to synchronize their application state with an external data store. React's useSyncExternalStore hook provides a seamless solution to this challenge. In this article, we'll explore what the useSyncExternalStore h
4 min read
ReactJS useUndoState hook
The useUndoState hook is a custom hook provided by the Rooks package for React. It is similar to the useState hook in addition to undo functionality. Arguments: initialValue: It is of the type boolean that describes the initial value of the state. Its default value is false.Options: It is of the typ
2 min read
ReactJS useReducer Hook
The useReducer hook is an alternative to the useState hook that is preferred when you have complex state logic. It is useful when the state transitions depend on previous state values or when you need to handle actions that can update the state differently.Syntaxconst [state, dispatch] = useReducer(
5 min read