---
title: "Use cases for the useInsertionEffect React hook"
description: "Practical use cases for React's useInsertionEffect hook — what it's for, how it differs from useEffect and useLayoutEffect, and when to use it, with an honest look at the downsides."
canonical: "https://asmyshlyaev177.dev/blog/use-cases-useinsertioneffect-react-hook"
published: "August 21, 2024"
tags: ["React", "JavaScript"]
---

# Use cases for the useInsertionEffect React hook

> Practical use cases for React's useInsertionEffect hook — what it's for, how it differs from useEffect and useLayoutEffect, and when to use it, with an honest look at the downsides.

---

## Intro

Everybody familiar with `useEffect` hook, sometimes `useLayoutEffect` is more appropriate.

Not so many people ever used `useInsertionEffect`, let's explore it.

API for hook is very similar to `useEffect`, need to add code into setup function, dependencies array and it can return a cleanup function.

[React docs](https://react.dev/reference/react/useInsertionEffect) give this description.

> `useInsertionEffect` is for CSS-in-JS library authors.

It can be useful for other purposes, mainly to run some code once on component mount, e.g. add event listener to a `window`.

## Use cases

### `Shiki` code highlighter

```typescript
React.useInsertionEffect(() => {
  initShiki().then((highlight) => {
    setHtml(highlight(content));
  });
}, [content]);
```

### Event listeners for window

```typescript
useInsertionEffect(() => {
  const popCb = () => {
    const newVal = parse(filterUnknownParamsClient(defaultState));
    state.current = newVal;
  };

  window.addEventListener(popstateEv, popCb);

  return () => {
    window.removeEventListener(popstateEv, popCb);
  };
}, []);
```

### Some custom subscriptions

```typescript
useInsertionEffect(() => {
  const cb = () => {
    _setState(stateMap.get(stateShape.current) || stateShape.current);
  };
  const unsub = subscribers.add(stateShape.current, cb);

  return () => {
    unsub();
  };
}, []);
```

## Pros and cons

- The main benefit of this hook is to run code before component rendered, and before other hooks.
- You're not supposed to use `useState.setState` from inside this hook, but it is work, maybe it will change in the future.
- Refs aren't attached by the time hook run.

---

Author: Aleksandr Smyshliaev — <https://asmyshlyaev177.dev>
More posts: <https://asmyshlyaev177.dev/blog> · Site summary for LLMs: <https://asmyshlyaev177.dev/llms.txt>
