Making use of Observers in React

Jens Lind
Strise

--

Ever needed to manipulate the DOM when scrolling passed a specific element? In the past, we had to add scroll listeners and do some hefty calculations. Not anymore, with the introduction of Observers in modern browsers, we can now solve this much more efficiently.

Recently we implement a new feature which required exactly the “is this element in view” functionality. After doing some research I found out about the Intersection Observer API! Our product is running React, and since we are all into hooks, this had to be solved by one! 🎣

Access the DOM node in React

To access actual DOM nodes in React, we use the ref prop. Usually you would probably pass a ref object using createRef or useRef but the ref prop can also take a function, this is referred to as a “callback ref”. This function will fire when the element mounts and unmounts from the DOM.

The Intersection Observer API

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport. — MDN

In practice this allows us to check if an element is visible in the viewport or not. The viewport could be the whole window, or any parent element relative to the target element. Go checkout the MDN docs to learn more about the API.

Creating the hook 🎣

Quite a simple one! As you can see we keep the observer in a ref object using theuseRef hook, thats because useRef is not just for DOM refs. You can store anything in a ref object, the advantage of this is that it will remain the same across renders.

But what if the node unmounts from the DOM?

If node is null the element has been unmounted, we can then disconnect the observer which cancels all current observes of this instance.

Finally, we can use the hook like this:

Come help us build Strise!

We are growing! Want to work with React, props-based styling, or build on a design system? Then we would love talking to you! We are helping banks & sales-teams across Norway & Sweden with KYC and prospecting of new customers, and are about to expand into new markets.

jobs@strise.ai
instagram.com/strise.ai

A few great resources on the subject:

--

--