Sitemap
Nikita Jaiswal

Nikita Jaiswal

Software Engineer

useInsertionEffect Hook

2 min readDec 24, 2023
Press enter or click to view image in full size

In this tutorial, we are going to take a look at the “useInsertionEffect” Hook.

This Hook provides a very convenient way to execute a code immediately right after a component element has been inserted into the DOM.

Let’s see an example:

Press enter or click to view image in full size

In the example provided, there’s a simple component named “UseInsertionEffectExample” using two hooks: “useInsertionEffect” and “useEffect”. Each hook logs something, along with an initial log stating “Pre render”. When checking the browser console, the “Pre render” log appears first, followed by the log from useInsertionEffect, and lastly, the log from useEffect.

Now, why would we use this hook 🙃?

It’s ideal for handling actions right after an element gets added to the DOM, particularly in scenarios involving CSS-in-JS libraries.

This hook works similarly to useEffect but executes synchronously before any changes are made to the DOM. Therefore, if you’re not adding any CSS styles to the DOM, it might not be necessary to use this hook.

Get Nikita Jaiswal’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s see one example of real use:

Press enter or click to view image in full size

In the above example, I have a button that will toggle the button color between black and white, and based on that I am rendering the CSS and adding it to my page.

When you inspect the element and look into the head tag, you’ll notice that a style gets included in the DOM when the button is toggled. Please see the below output

Press enter or click to view image in full size
Press enter or click to view image in full size

Conclusion

The useInsertionEffect hook is used to manipulate the DOM elements

Thank you 🙂

--

--