ā¤ Like
šŸ”– Save
šŸ”— Share
Eric Hu
Eric Hu

React Effect Hooks

@thedevspaceio

āš›ļø 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.

HookDescription
useEffectSynchronize with external systems after rendering.
useLayoutEffectRun effects before the browser paints.
useInsertionEffectInsert CSS-in-JS styles before layout effects run.
useEffectEventRead the latest values inside an effect without re-running it.

useEffect

Run side effects after the component renders and the browser paints.

jsx
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

jsx
useEffect(() => {
  // effect logic here
});

Empty array: Runs only once, after the initial render

jsx
useEffect(() => {
  // effect logic here
}, []);

Dependency array with states or props: Runs when any dependency changes

jsx
useEffect(() => {
  // effect logic here
}, [a, b]);

Cleanup function

Return a function to clean up before the effect re-runs or the component unmounts.

jsx
useEffect(() => {
  const subscription = subscribe();
 
  return () => subscription.unsubscribe();
}, []);

Fetching data

Fetch inside an effect and handle cleanup with an ignore flag.

jsx
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.

jsx
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.

jsx
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.

jsx
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 changes

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io