useInsertionEffect
useEffect
executes a function after component rendering, whileuseInsertionEffect
is designed for inserting elements into the DOM before layout effects, like dynamic styles, without server rendering.useInsertionEffect
is specialized for pre-layout element insertion, running only on the client side and not during server rendering.
Import:
import { useInsertionEffect } from 'react';
Syntax:
useInsertionEffect(()=>{
// Insert dynamic styles before layout effects fire
return()=>{
//cleanup function
}
}, [])
Example: This exampe implements UseInsertionEffectHook in React
Javascript
import React from 'react' ; import UseInsertionEffectHook from './BatteryStatusIndicator' ; function App() { return ( <div> <UseInsertionEffectHook/> <br/> <br/> <button>First</button> <button>Second</button> </div> ); } export default App; |
Javascript
import { useInsertionEffect, useState } from "react" ; export default function UseInsertionEffectHook() { const [theme, setTheme] = useState( 'dark' ) useInsertionEffect(() => { const styleRule = getStyleRule(theme); document.head.appendChild(styleRule); return () => document.head.removeChild(styleRule) }, [theme]) return <button onClick={ () => setTheme(theme === 'dark' ? 'white' : 'dark' )}> Change theme </button> } const getStyleRule = (theme) => { const tag = document.createElement( 'style' ) tag.innerHTML = ` button { color: ${theme === 'dark' ? 'white' : 'black' }; background-color : ${theme === 'dark' ? 'black' : 'white' }; } ` return tag } |
Output:
New Hooks in React 18
React’s state, representing dynamic component data, is integral for effective component management. Initially confined to class components and managed using this.setState
, the introduction of React Hooks in version 16.8 extended state usage to functional components. Hooks, functions enabling state and lifecycle management in functional components, provide a more versatile approach to React development.
There are several built-in hooks in React, today we are going to see new React hooks that are introduced in React 18.
Table of Content
- useId
- useDeferredValue
- useTransition
- useSyncExternalStore
- useInsertionEffect