
React Effect Hooks
āļø Connecting React to the Outside World
Effect hooks let you synchronize components with external systems. Giving your app a portal to synchronize with external systems, like data fetching, subscriptions, and DOM manipulation after rendering.
ā useEffect ā useLayoutEffect ā useInsertionEffect ā useEffectEvent
#react #hooks #useeffect #uselayouteffect #useeffectevent #webdev #frontend #coding #tips
Effect hooks let components run side effects. Giving your app a portal to synchronize with external systems, like data fetching, subscriptions, and DOM manipulation after rendering.
| Hook | Description |
|---|---|
useEffect | Synchronize with external systems after rendering. |
useLayoutEffect | Run effects before the browser paints. |
useInsertionEffect | Insert CSS-in-JS styles before layout effects run. |
useEffectEvent | Read the latest values inside an effect without re-running it. |
useEffect
Run side effects after the component renders and the browser paints.
import { useState, useEffect } from "react";
function App() {
const [count, setCount] = useState(0);
// Run side effect when count changes
useEffect(() => {
document.title = `Count: ${count}`;
console.log(`Count updated to: ${count}`);
}, [count]);
return (
<div style={{ padding: "20px" }}>
<h2>useEffect Example</h2>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default App;Dependency array
The array of dependencies controls when the effect re-runs.
No dependency array defined: Runs after every render
useEffect(() => {
// effect logic here
});Empty array: Runs only once, after the initial render
useEffect(() => {
// effect logic here
}, []);Dependency array with states or props: Runs when any dependency changes
useEffect(() => {
// effect logic here
}, [a, b]);Cleanup function
Return a function to clean up before the effect re-runs or the component unmounts.
useEffect(() => {
const subscription = subscribe();
return () => subscription.unsubscribe();
}, []);Fetching data
Fetch inside an effect and handle cleanup with an ignore flag.
useEffect(() => {
let ignore = false;
fetch(`/api/users/${id}`)
.then((res) => res.json())
.then((data) => {
if (!ignore) setUser(data);
});
return () => {
ignore = true;
};
}, [id]);This prevents updating state on an unmounted component if the fetch is still in progress.
useLayoutEffect
Identical to useEffect, but runs synchronously before the browser paints. Use it for DOM measurements.
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTooltipHeight(height);
}, []);ā Prefer useEffect by default. useLayoutEffect blocks painting and can hurt performance.
useInsertionEffect
Runs before any layout effects. Intended for CSS-in-JS libraries to inject styles.
useInsertionEffect(() => {
const style = document.createElement("style");
style.textContent = css;
document.head.appendChild(style);
return () => style.remove();
}, [css]);ā Not for application code. Use only when building a styling library.
useEffectEvent
Extract non-reactive logic out of an effect. The event always reads the latest props and state.
const onMessage = useEffectEvent((msg) => {
showNotification(msg, theme); // always the latest theme
});
useEffect(() => {
chat.on("message", onMessage);
return () => chat.off("message", onMessage);
}, []); // does not re-run when theme changesFull-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.