When to Avoid useInsertionEffect in React

This article explains the specific purpose of React’s useInsertionEffect hook and details the scenarios where you should avoid using it. While it is an essential tool for CSS-in-JS library authors, using it in standard application code can lead to performance bottlenecks and unexpected bugs.

useInsertionEffect is a specialized hook introduced in React 18. It runs synchronously before any layout effects (like useLayoutEffect) and before the browser repaints the screen. Its sole purpose is to inject <style> tags into the DOM dynamically.

You should avoid using useInsertionEffect in the following scenarios:

1. You are Writing Standard Application Code

If you are building a typical React application and not authoring a CSS-in-JS library, you should avoid useInsertionEffect entirely. For fetching data, handling event listeners, triggering animations, or managing state updates, use standard hooks like useEffect or useLayoutEffect. React’s official documentation explicitly states that this hook is intended purely for library developers.

2. You Need to Access DOM Layout and Measurements

If your code needs to measure the size or position of a DOM element (such as using getBoundingClientRect), do not use useInsertionEffect. Because this hook runs before the layout phase, the DOM elements have not been fully arranged by the browser. Reading layout properties at this stage will return inaccurate or obsolete dimensions. Use useLayoutEffect instead.

3. You Need to Read or Mutate Refs

Do not attempt to access or modify React ref objects inside useInsertionEffect. At the point this hook executes, React has not yet updated the .current property of refs for the newly rendered elements. If you try to access a DOM node via a ref within this hook, it will likely be null or point to stale data.

4. You Want to Update Component State

Do not trigger state updates (using setState functions) inside useInsertionEffect. Doing so disrupts React’s rendering pipeline, forcing premature re-renders before the layout phase is completed, which can lead to severe performance degradation and visual flickering.