useInsertionEffect Hooks
The useInsertionEffect Hook in React 18 is designed to insert elements such as dynamic styles into the DOM before the layout effects are triggered. This hook is particularly useful for client-side operations where pre-layout element insertion is crucial.
- Triggering on DOM Insertion: Similar to how
useEffect
triggers after a component has been mounted or updated,useInsertionEffect
might trigger when a specific element is inserted into the DOM for the first time. - Handling Cleanup: Just like
useEffect
,useInsertionEffect
might also support cleanup functionality to remove any event listeners or clean up resources when the component or element is unmounted or removed from the DOM.
Syntax:
useInsertionEffect(setup, dependencies?)
Example: Below is an example of useInsertionEffect Hooks.
Javascript
//App.js import React, { useState } from 'react' ; import { useInsertionEffect } from 'react' ; const 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, w3wiki!</h1> <h3>useInsertionEffect Hook - Example 1</h3> <button onClick={btnFn}>Change Color</button> </div> ); } export default App; |
Output:
Effect Hooks in React
Effect Hooks in React allow components to interact with and stay synchronized with external systems, such as handling network requests, manipulating the browser’s DOM, managing animations, integrating with widgets from other UI libraries, and working with non-React code. Essentially, effects help components communicate and coordinate with the world outside of React.
- useEffect is used to connect components to an external system.
- useLayoutEffect performs a side effect immediately after the browser has painted the screen.
- useInsertionEffect is used before ReactJS makes changes to the DOM, and in this libraries can insert the dynamic CSS.
We will discuss about the following types of Effect Hooks in React.
Table of Content
- useEffect Hooks
- useLayoutEffect Hooks
- useInsertionEffect Hooks