ReactJS - useInsertionEffect Hook



The ‘useInsertionEffect’ hook is introduced in the 18th version of React JS. The useInsertionEffect hook provides a new and user-friendly approach to manage DOM insertion operations. Developers can useInsertionEffect to execute actions immediately after an element is placed into the DOM.

The useInsertionEffect hook is a custom hook that allows us to run code immediately after a component's element is placed into the DOM tree. It is inspired by the built-in hooks in React, like useEffect and useLayoutEffect.

Syntax

useInsertionEffect(setup, dependency)

Parameter

  • Setup − This is the part where we can place the code that tells our React component to do anything when it is initially introduced to the web page.

  • Optional Dependencies − This is similar to a list of objects on which our setup code is dependent. It might be anything from outside our component such as information, data or something we generate within the component.

Return Value

This hook returns undefined.

Examples

Example − Add CSS to textArea

This software lets us enter CSS code into a textarea and view how it looks on a div element. After the div element has been placed into the DOM, the useInsertionEffect hook is used to insert the CSS code into the document's head. This guarantees that the CSS code is applied before any other layout effects are done.

import React, { useState, useRef, useInsertionEffect } from 'react';

const App = () => {
   const [styleText, setStyleText] = useState('');
   const styleRef = useRef(null);
   
   useInsertionEffect(() => {
      const styleElement = document.createElement('style');
      styleElement.textContent = styleText;
      document.head.appendChild(styleElement);
      
      return () => {
         document.head.removeChild(styleElement);
      };
   }, [styleText]);
   
   return (
      <div>
         <textarea
            value={styleText}
            onChange={(event) => setStyleText(event.target.value)}
         />
         <div ref={styleRef} />
      </div>
   );
};

export default App;

Output

reactapp

Example − Dynamic Progress Bar App

Here is another example of an app using the useInsertionEffect hook in React that shows its usage for creating a dynamic progress bar. This app allows us to adjust a range input, and the value of the input will be reflected in a dynamic progress bar. The useInsertionEffect hook is used to update the width of the progress bar whenever the progress state variable changes.

import React, { useState, useRef, useEffect } from 'react';

const App = () => {
   const [progress, setProgress] = useState(0);
   const progressBarRef = useRef(null);
   
   useEffect(() => {
      const progressBarElement = progressBarRef.current;
      progressBarElement.style.width = `${progress}%`;
   }, [progress]);
   
   return (
      <div>
         <input type="range" min="0" max="100" value={progress} onChange={(event) => setProgress(event.target.value)} />
         <div ref={progressBarRef} style={{ height: 20, backgroundColor: '#ccc' }}>
            <div style={{ height: '100%', width: `${progress}%`, backgroundColor: '#007bff' }}></div>
         </div>
      </div>
   );
};

export default App;

Output

progress bar app

Example

So we can use the ‘useInsertionEffect’ hook by using CSS-in-JS libraries to inject dynamic styles. So we will discuss this in detail with the help of a short application.

In the past, React components were styled using basic CSS.

// In the Javascript file:
<button className="login" />

// In the CSS file:
.login { color: green; }

In simple terms, CSS-in-JS is a way to style the JavaScript components. While static and inline styles are preferred, inserting styles during runtime can lead our program to slow down. In React, the useInsertionEffect hook manages when these styles are added, making our app easier to use.

import React from 'react';
import { useInsertionEffect } from 'react'; // import here the useInsertedEffect hook
let isInserted = new Set();

function useCSS(rule) {
   useInsertionEffect(() => {
      if (!isInserted.has(rule)) {
         isInserted.add(rule);
         const style = document.createElement('style');
         style.innerHTML = rule;
         document.head.appendChild(style);
      }
   });
}

function ColoredBox() {
   useCSS('.colored-box { background-color: lightgreen; }');

   return <div className="colored-box">I have a colored background.</div>;
}

function App() {
   return (
      <div>
         <ColoredBox />
      </div>
   );
}
export default App;

Output

background color

In the above example, we have a ColoredBox component that uses the useCSS custom hook to dynamically put a CSS rule that changes the background colour. The useInsertionEffect hook makes sure that the CSS rule comes before the layout effect.

Limitations

  • Effects, like those used with useInsertionEffect, are only applicable to the web page displayed in our browser. They are not executed when the webpage is actually created on the server before being transmitted to our browser.

  • We cannot modify the data or information that our component uses from within a useInsertionEffect.

  • When a useInsertionEffect hook is executed, the special references (refs) are not yet ready. They are not immediately used.

  • We can never be sure when usingInsertionEffect will be activated when the webpage is updated. It can run before or after things have changed on the page.

Summary

The useInsertionEffect hook in React applications provides a powerful and easy approach to manage DOM insertion actions. We can do DOM modifications, animations, initialization, and clean-up activities by running code right after an element is added into the DOM. Understanding its settings, limitations, and real-world best practices will enable us to properly harness useInsertionEffect and improve the functionality and user experience of your React components.

reactjs_reference_api.htm
Advertisements