console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);
?
- Web API docs
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
import { useState, useEffect, RefObject } from 'react';
export const useVisible = (
ref: RefObject<HTMLDivElement>,
options = {
root: null,
rootMargin: '0px',
threshold: 1.0
}
) => {
const [isVisible, setIsVisible] = useState<boolean>(false);
useEffect(() => {
const { current: elementRef } = ref;
if (elementRef) {
const observer = new IntersectionObserver(
([entry]) => setIsVisible(entry.isIntersecting), options
);
observer.observe(elementRef);
return () => observer.unobserve(elementRef);
}
}, [ref, options]);
return isVisible;
};
Lazy-load images
Infinite scroll lists
Defer animations
Save compute power
03
02
04
01
Provides events you can watch for to know the current visibility state of the page
Triggers when user
switches tab
minimizes window
puts another window as overlay
locks/turns off device
import { useEffect, useState } from "react";
export const usePageVisibility = () => {
const [pageVisible, setPageVisible] = useState<boolean>(true);
useEffect(() => {
const handleVisibilityChange = () => {
const isPageVisible = document.visibilityState === "visible";
setPageVisible(isPageVisible);
};
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, []);
return pageVisible;
};
Improving performance
01
Pause audio/video
02
Detect page visit count
03
Poll server data
04
Carousel
05
Prevent devices from locking the screen when an application needs to keep running
import { useEffect, useCallback, useRef } from 'react';
export const useWakeLock = (shouldWakeLock = false) => {
let sentinel = useRef<WakeLockSentinel | null>(null);
const requestWakeLockSentinel = useCallback(async () => {
sentinel.current = await navigator.wakeLock.request('screen');
}, []);
const releaseWakeLockSentinel = useCallback(async () => {
await sentinel.current?.release();
sentinel.current = null;
}, []);
useEffect(() => {
(async () => {
if (shouldWakeLock) {
await requestWakeLockSentinel();
return releaseWakeLockSentinel;
}
await releaseWakeLockSentinel();
})();
}, [shouldWakeLock, requestWakeLockSentinel, releaseWakeLockSentinel]);
return { isWakeLock: !!sentinel.current };
};
Reading an ebook
Presenting to an audience
Following a recipe
Map navigation
Scanning a QR / barcode
03
05
02
04
01
Network API
Beacon API
Media Session API
Background Sync API
Background Fetch API
Broadcast Channel API
Standardized code
Standardized code
Standardized code
Smooth learning curve
Increase performance of web apps
Internet is consuming 21% of the electricity
check out carbon footprint
website traffic
energy intensity
data transfers
n.mitrovic@vegait.rs
You can find me at
Link to the slides