REACT COOL INVIEW
A React hook that monitors an element enters or leaves the viewport (or another element) with highly-performant way, using Intersection Observer. It's lightweight and super flexible, which can cover all the cases that you need, like lazy-loading images and videos, infinite scrolling web app, triggering animations, tracking impressions, and more.
Features
- ? Monitors elements with highly-performant and non-main-thread blocking way, using Intersection Observer.
- ? Easy to use, based on React hook.
- ? Super flexible API design which can cover all the cases that you need.
- ?️ Supports scroll direction, cool right?
- ✌? Supports Intersection Observer v2.
- ? Supports custom
refs
for some reasons. - ? Supports TypeScript type definition.
- ?️ Server-side rendering compatibility.
- ? Tiny size (~ 1KB gzipped). No external dependencies, aside for the
react
.
Requirement
To use react-cool-inview
, you must use react@16.8.0
or greater which includes hooks.
Installation
This package is distributed via npm.
Usage
react-cool-inview
has a flexible API design, it can cover simple to complex use cases for you. Here are some ideas for how you can use it.
⚠️ Most modern browsers support Intersection Observer natively. You can also add polyfill for full browser support.
Basic Use Case
To monitor an element enters or leaves the viewport by the inView
state and useful sugar events.
Lazy-loading Images
It's super easy to build an image lazy-loading component with react-cool-inview
to boost the performance of your web app.
? Looking for a comprehensive image component? Try react-cool-img, it's my other component library.
Infinite Scrolling
Infinite scrolling is a popular design technique like Facebook and Twitter feed etc., new content being loaded as you scroll down a page. The basic concept as below.
Compare to pagination, infinite scrolling provides a seamless experience for users and it’s easy to see the appeal. But when it comes to render a large lists, performance will be a problem. We can use react-window to address the problem by the technique of DOM recycling.
Trigger Animations
Another great use case is to trigger CSS animations once they are visible to the users.
Track Impressions
react-cool-inview
can also play as an impression tracker, helps you fire an analytic event when a user sees an element or advertisement.
Scroll Direction
react-cool-inview
not only monitors an element enters or leaves the viewport but also tells you its scroll direction by the scrollDirection
object. The object contains vertical (y-axios) and horizontal (x-axios) properties, they're calculated whenever the target element meets a threshold
. If there's no enough condition for calculating, the value of the properties will be undefined
.
Intersection Observer v2
The Intersection Observer v1 can perfectly tell you when an element is scrolled into the viewport, but it doesn't tell you whether the element is covered by something else on the page or whether the element has any visual effects applied on it (like transform
, opacity
, filter
etc.) that can make it invisible. The main concern that has surfaced is how this kind of knowledge could be helpful in preventing clickjacking and UI redress attacks (read this article to learn more).
If you want to track the click-through rate (CTR) or impression of an element, which is actually visible to a user, Intersection Observer v2 can be the savior. Which introduces a new boolean field named isVisible. A true
value guarantees that an element is visible on the page and has no visual effects applied on it. A false
value is just the opposite. The characteristic of the isVisible
is integrated with the inView
state and related events (like onEnter, onLeave etc.) to provide a better DX for you.
When using the v2, there're something we need to know:
- Check browser compatibility. If a browser doesn't support the v2, we will fallback to the v1 behavior.
- Understand how visibility is calculated.
- Visibility is much more expensive to compute than intersection, only use it when needed.
To use Intersection Observer v2, we must set the trackVisibility
and delay
options.
Use Your Own ref
In case of you had a ref already or you want to share a ref for other purposes. You can pass in the ref instead of using the one provided by this hook.
API
Return object
It's returned with the following properties.
Key | Type | Default | Description |
---|---|---|---|
ref |
object | Used to set the target element for monitoring. | |
inView |
boolean | The visible state of the target element. If it's true , the target element has become at least as visible as the threshold that was passed. If it's false , the target element is no longer as visible as the given threshold. Supports Intersection Observer v2. |
|
scrollDirection |
object | The scroll direction of the target element. Which contains vertical and horizontal properties. See scroll direction for more information. |
|
entry |
object | The IntersectionObserverEntry of the target element. Which may contain the isVisible property of the Intersection Observer v2, depends on the browser compatibility. | |
unobserve |
function | To stop observing the target element. | |
observe |
function | To re-start observing the target element once it's stopped observing. |
Parameter
The options
provides the following configurations and event callbacks for you.
Key | Type | Default | Description |
---|---|---|---|
ref |
object | For some reasons, you can pass in your own ref instead of using the built-in. |
|
root |
HTMLElement | window |
The element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target. Defaults to the browser viewport if not specified or if null . |
rootMargin |
string | 0px |
Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). The values can be percentages. This set of values serves to grow or shrink each side of the root element's bounding box before computing intersections. |
threshold |
number | number[] | 0 |
Indicates at what percentage of the target's visibility the observer's callback should be executed. If you only want to detect when visibility passes the 50% mark, you can use a value of 0.5. If you want the callback to run every time visibility passes another 25%, you would specify the array [0, 0.25, 0.5, 0.75, 1]. |
trackVisibility |
boolean | false |
Indicates whether the intersection observer will track changes in a target’s visibility. It's required when using Intersection Observer v2. |
delay |
number | Indicates the minimum delay in milliseconds between notifications from the intersection observer for a given target. It's required when using Intersection Observer v2. | |
unobserveOnEnter |
boolean | false |
Stops observe once the target element intersects with the intersection observer's root. It's useful when you only want to trigger the hook once, e.g. scrolling to run animations. |
onChange |
function | It's invoked whenever the target element meets a threshold specified for the intersection observer. The callback receives an event object which the same with the return object of the hook. | |
onEnter |
function | It's invoked when the target element enters the viewport. The callback receives an event object which the same with the return object of the hook except for inView . Supports Intersection Observer v2. |
|
onLeave |
function | It's invoked when the target element leaves the viewport. The callback receives an event object which the same with the return object of the hook except for inView . Supports Intersection Observer v2. |
Intersection Observer Polyfill
Intersection Observer has good support amongst browsers, but it's not universal. You'll need to polyfill browsers that don't support it. Polyfills is something you should do consciously at the application level. Therefore react-cool-inview
doesn't include it.
You can use W3C's polyfill:
Then import it at your app's entry point:
Or use dynamic imports to only load the file when the polyfill is required:
Polyfill.io is an alternative way to add the polyfill when needed.
Performance Issues
Be aware that the callback of the onChange
event is executed on the main thread, it should operate as quickly as possible. If any time-consuming needs to be done, use requestIdleCallback or setTimeout.