Trigger Event When Element Enters Viewport. The React Way.

Rasil Baidar
1 min readDec 9, 2022


Triggering event when an element enters a viewport is a technique any frontend developer must know. As this technique can be used in many areas of frontend development such as ( infinite scrolling, rendering animation e.t.c).

In this blog I will show you how we can achieve this using Reacts useRef hook and IntersectionObserver.

First, let’s create a custom hook so that we can re-use this utility anywhere in our code base.

Here, the parameters passed to the custom hook are :-

element : ref of an element we want to observe

rootMargin : offset value which signifies at what point should the element be registered as visible.

Now let’s create a dummy element which we want to observe.

Here, we passed ref of the element we want to observe to our custom hook and passed what offset should the element be registered as visible.

Thats all, folks. Go ahead and use this in your code when you want to trigger an event or function when your element enters your viewport.

Happy coding.



Rasil Baidar

Web App Developer | Smart Contract Developer | Fitness Enthusiast