DEV Community

Alex
Alex

Posted on

Use cases for `useInsertionEffect` React hook

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

  React.useInsertionEffect(() => {
    initShiki().then((highlight) => {
      setHtml(highlight(content));
    });
  }, [content]);
Enter fullscreen mode Exit fullscreen mode

Event listeners for window

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

    window.addEventListener(popstateEv, popCb);

    return () => {
      window.removeEventListener(popstateEv, popCb);
    };
  }, []);
Enter fullscreen mode Exit fullscreen mode

Some custom subscriptions

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

    return () => {
      unsub();
    };
  }, []);
Enter fullscreen mode Exit fullscreen mode

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay