![]() |
VOOZH | about |
The useInsertionEffect hook is designed specifically for CSS-in-JS library authors to synchronously inject global DOM nodes, like dynamic <style> tags or SVG <defs>βon the client side. By executing just before any layout effects fire, it ensures styles are inserted at the exact right moment during the rendering process.
useInsertionEffect(setup, dependencies?)
// Example
useInsertionEffect(() => {
// insert dynamic styles before layout effects fire
return () => {
// cleanup
};
}, []);
[ ]) .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.
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.
Output: