Zum Hauptinhalt springen
LIVE
CVSS 6.9CVE-2026-138103 | A vulnerability was detected in ssssssss-team magic-api up to 2.2.2. This issue affects the function saveFile of the file MagicResourceController.java of the component magic-api-core resource save API. The manipulation results in code injection. It is possible to launch the attack remotely. The exploit is now public and may be used. The project was informed of the problem early through an issue report but has not responded yet.CVSS 9.4CVE-2026-138102 | A security vulnerability has been detected in D-Link DIR-620S 4.0.2. This vulnerability affects unknown code of the file /usr/sbin/anweb of the component Diagnostic Handler. The manipulation of the argument I leads to os command injection. It is possible to initiate the attack remotely. The exploit has been disclosed publicly and may be used.CVSS 5.3CVE-2026-138101 | A weakness has been identified in MassGen up to 0.1.97. This affects the function _generate_subagent_yaml_config of the file massgen/subagent/manager.py of the component Subagent Delegation System. Executing a manipulation can lead to improper authorization. The attack may be performed from remote. The exploit has been made available to the public and could be used for attacks. The project was informed of the problem early through an issue report but has notCVSS 6.9CVE-2026-138100 | A security flaw has been discovered in MassGen up to 0.1.97. Affected by this issue is the function __init__ of the file massgen/filesystem_manager/_filesystem_manager.py. Performing a manipulation results in protection mechanism failure. The attack is possible to be carried out remotely. The exploit has been released to the public and may be used for attacks. The project was informed of the problem early through an issue report but has not responded yet.CVSS 8.7CVE-2026-138099 | A vulnerability was identified in Tenda AC10U 1.18.6. Affected by this vulnerability is the function readUsb of the component ATE Service. Such manipulation leads to out-of-bounds write. The attack can be executed remotely. The exploit is publicly available and might be used.CVSS 6.9CVE-2026-138098 | A vulnerability was determined in weison-tech yii2-cms up to 1.0.2. Affected is an unknown function of the file protected/core/config/common.php of the component RBAC Authorization. This manipulation causes improper authorization. Remote exploitation of the attack is possible.CVSS 6.9CVE-2026-138097 | A vulnerability was found in weison-tech yii2-cms up to 1.0.2. This impacts the function isActive of the file AccessControl.php of the component RBAC Admin Module. The manipulation results in missing authorization. The attack may be launched remotely.CVSS 6.9CVE-2026-138096 | A vulnerability has been found in weison-tech yii2-cms up to 1.0.2. This affects an unknown function of the file protected/core/config/web.php of the component Admin Auto-Login Identity Cookie. The manipulation leads to improper authentication. The attack may be initiated remotely.
Alle im Drawer
Intelligence View
⚡ tsecurity.de Intelligence

React useIntersectionObserver Hook: Lazy Load & Detect Visibility (2026)

React useIntersectionObserver Hook: Lazy Load & Detect Visibility (2026) You want to load an image only when it scrolls near the viewport. Or fire an analytics…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Quelle & Fakten · 10 Min. Lesezeit
Quelle: dev.to
Rubrik: Programmation sécurisée




React useIntersectionObserver Hook: Lazy Load & Detect Visibility (2026)



You want to load an image only when it scrolls near the viewport. Or fire an analytics event the first time a card is actually seen. Or trigger "load more" when the user reaches the bottom of a list. Every one of these is the same question — is this element on screen yet? — and for years the answer was a scroll listener that fired hundreds of times a second, re-read getBoundingClientRect() on each tick, and still managed to miss the edge cases.



IntersectionObserver is the browser API that answers that question correctly, asynchronously, and off the main thread. useIntersectionObserver is the hook that wires it into React without the useEffect/useRef/cleanup boilerplate — and without the leak-on-unmount and stale-closure bugs the hand-rolled version always ships. This post covers the real @reactuses/core API, the three patterns you'll actually reach for, and how to tune threshold, rootMargin, and root. SSR-safe and typed.






Why Not Just Use a Scroll Listener?



The old way to know whether an element was visible looked like this: listen to scroll, and on every event measure the element against the viewport.




useEffect(() => {
function onScroll() {
const rect = el.getBoundingClientRect();
if (rect.top < window.innerHeight) {
setVisible(true);
}
}
window.addEventListener('scroll', onScroll);
return () => window.removeEventListener('scroll', onScroll);
}, []);






This has two problems baked in. First, scroll fires on the main thread, dozens of times per second, and getBoundingClientRect() forces a synchronous layout each time — that's exactly the recipe for janky scrolling. Second, it only catches elements crossing the viewport; the moment your scroll happens inside a container, you're re-deriving geometry by hand.



IntersectionObserver flips the model. You hand the browser a target and a threshold, and it tells you — asynchronously, batched, off the scroll path — when the element crosses that threshold. No measuring, no listener thrash. The only thing left to get wrong is the React lifecycle around it, and that's the part the hook owns.



Here's the naive in-component version, which has the same three bugs every hand-rolled observer does:




function LazySection({ children }: { children: React.ReactNode }) {
const ref = useRef<HTMLDivElement>(null);
const [seen, setSeen] = useState(false);

useEffect(() => {
const el = ref.current;
if (!el) return;
const io = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) setSeen(true); // 🐛 see below
}, { threshold: 0.1 });
io.observe(el);
return () => io.disconnect();
}, []);

return <div ref={ref}>{seen ? children : null}</div>;
}








  1. It leaks if you forget the cleanup. Drop the return () => io.disconnect() — and people do, especially when refactoring — and the observer outlives the component.


  2. It captures stale closures. The moment the callback references a prop or a second piece of state, the observer created on mount freezes whatever those were at mount time, not when it fires.


  3. It spreads. Every lazy section, every "viewed" tracker, every infinite-scroll sentinel re-implements the same useRef + observe + disconnect dance, and each copy is a fresh chance to ship one of the first two bugs.



A hook fixes all three in one place.






The API



useIntersectionObserver takes three arguments and returns a stop function:




const stop = useIntersectionObserver(target, callback, options?);








  • target — what to observe. A React ref, a raw element, or a getter () => element. (It accepts null/undefined too, so observing a conditionally-rendered element is safe — the hook simply waits.)


  • callback — the standard IntersectionObserverCallback, (entries, observer) => void. You get the raw IntersectionObserverEntry[], so you decide what visibility means for your case.


  • options — the native IntersectionObserverInit: { root, rootMargin, threshold }. All optional.


  • returns stop() — call it to disconnect the observer early (more on this below). The hook also calls it for you automatically on unmount.



The deliberate design choice here is that the hook is callback-based, not boolean-based. It doesn't decide for you that "intersecting" means visible — because depending on the job, it might mean "10% visible", "fully visible", or "within 200px of the viewport". You read entry.isIntersecting (or entry.intersectionRatio) and act. If all you want is a plain boolean, there's a convenience sibling for that — see below.



Internally the callback is kept in a ref (via useLatest), so it never goes stale — bug #2 is gone even when your callback closes over props. And because the observer is only ever constructed inside an effect, the hook is SSR-safe: nothing touches IntersectionObserver during render.






Pattern 1: Lazy-Load an Image



The canonical use. Render a placeholder, and only swap in the real <img> once the container is about to enter the viewport. Note the stop() call — once we've loaded, we never need the observer again, so we disconnect it immediately.




import { useRef, useState } from 'react';
import { useIntersectionObserver } from '@reactuses/core';

function LazyImage({ src, alt }: { src: string; alt: string }) {
const ref = useRef<HTMLDivElement>(null);
const [loaded, setLoaded] = useState(false);

const stop = useIntersectionObserver(
ref,
([entry]) => {
if (entry.isIntersecting) {
setLoaded(true);
stop(); // one-shot: stop observing once we've committed to loading
}
},
{ rootMargin: '200px' }, // start loading 200px before it scrolls in
);

return (
<div ref={ref} style={{ minHeight: 200 }}>
{loaded ? <img src={src} alt={alt} /> : <div className="skeleton" />}
</div>
);
}






Two things make this feel right. The rootMargin: '200px' grows the observer's "viewport" by 200px on every side, so the fetch kicks off before the image is actually visible and the user rarely sees the skeleton. And stop() inside the callback means a list of 500 lazy images ends up with zero live observers once they've all loaded — no lingering work as you keep scrolling.






Pattern 2: Fire-Once "Viewed" Analytics



Tracking which sections a user actually scrolled to is the same shape — but here you genuinely want it to fire exactly once, so the stop() is doing real work.




import { useRef } from 'react';
import { useIntersectionObserver } from '@reactuses/core';

function TrackedSection({ id, children }: { id: string; children: React.ReactNode }) {
const ref = useRef<HTMLElement>(null);

const stop = useIntersectionObserver(
ref,
([entry]) => {
if (entry.isIntersecting) {
analytics.track('section_viewed', { id });
stop(); // count each section once, not once per scroll-past
}
},
{ threshold: 0.5 }, // "viewed" = at least half on screen
);

return <section ref={ref}>{children}</section>;
}






Here threshold: 0.5 encodes a product decision — a section only counts as "viewed" once 50% of it is on screen, so a fast scroll past the top edge doesn't inflate your numbers. The stop() guarantees one event per section per page load even if the user scrolls it in and out repeatedly.






Pattern 3: Infinite-Scroll Trigger



Put an empty sentinel <div> at the bottom of a list and fetch the next page when it intersects. Note that here we don't call stop() — we want the trigger to keep firing for every page.




import { useRef } from 'react';
import { useIntersectionObserver } from '@reactuses/core';

function Feed({ items, loadMore, hasMore }: FeedProps) {
const sentinel = useRef<HTMLDivElement>(null);

useIntersectionObserver(sentinel, ([entry]) => {
if (entry.isIntersecting && hasMore) {
loadMore();
}
});

return (
<>
{items.map((it) => <Row key={it.id} item={it} />)}
{hasMore && <div ref={sentinel} style={{ height: 1 }} />}
</>
);
}






Because the callback is always the latest one (no stale closure), loadMore and hasMore are read fresh every time the sentinel intersects — the bug that bites the hand-rolled useEffect version doesn't exist here. If you want this whole pattern packaged, useInfiniteScroll builds exactly this on top, including the scroll-container plumbing.






Tuning: threshold, rootMargin, and root



The third argument is the native IntersectionObserverInit, passed straight through. Three knobs, each answering a different question:




useIntersectionObserver(ref, callback, {
threshold: 0.5, // HOW MUCH must be visible to count?
rootMargin: '200px', // grow/shrink the trigger boundary
root: containerRef.current, // WHAT are we measuring against?
});








  • threshold — a number (or array) from 0 to 1 for how much of the target must be visible before the callback fires. 0 (the default) fires the instant a single pixel crosses; 1 waits until the element is fully on screen. Pass an array like [0, 0.25, 0.5, 0.75, 1] to get a callback at each step — useful for scroll-linked animations driven by entry.intersectionRatio.


  • rootMargin — a CSS-margin string that inflates or deflates the root's bounding box before intersection is computed. Positive values ('200px') fire early — the lazy-load-ahead trick from Pattern 1. Negative values ('-100px 0px') fire late, e.g. "only count this as viewed once it's 100px past the top edge."


  • root — the element you're measuring against. Defaults to the browser viewport; set it to a scroll container's element when your list scrolls inside a <div> rather than the page.






The stop() Return Value



The returned stop() disconnects the observer. You usually don't need it — the hook auto-disconnects on unmount — but it's the clean way to express one-shot observation, as in Patterns 1 and 2: the first time the element intersects, do the work and stop watching. That's both a correctness win (the event fires exactly once) and a performance one (no live observer trailing behind a long, already-loaded list).






Just Want a Boolean?



Sometimes you don't care about entries or thresholds — you just want a reactive isVisible flag for the whole viewport. useElementVisibility wraps useIntersectionObserver and hands you exactly that, as a tuple with its own stop:




import { useRef } from 'react';
import { useElementVisibility } from '@reactuses/core';

function FadeIn({ children }: { children: React.ReactNode }) {
const ref = useRef<HTMLDivElement>(null);
const [visible] = useElementVisibility(ref);

return (
<div ref={ref} className={visible ? 'fade fade-in' : 'fade'}>
{children}
</div>
);
}






Reach for useElementVisibility when a boolean is all you need, and drop down to useIntersectionObserver the moment you want a custom root, a non-default threshold, multiple thresholds, or the raw entry. Same engine, two ergonomics.






SSR Safety



useIntersectionObserver is safe to render on the server. It constructs the IntersectionObserver only inside an effect — which React never runs on the server — and the underlying element lookup returns undefined outside the browser, so there's no typeof window guard to write and no hydration mismatch to chase. Drop it into a Next.js, Remix, or Astro component as-is. (If SSR-safety is a recurring theme in your codebase, SSR-Safe React Hooks goes deeper.)






The Visibility & Size Family



useIntersectionObserver is the low-level primitive in a family of DOM-watching hooks. Pick by what you actually want back:











































Hook Gives you Reach for it when…
useIntersectionObserver raw entries, a stop()
you want full control: custom root, thresholds, one-shot
useElementVisibility [isVisible, stop] a plain "is it on screen?" boolean is enough
useInfiniteScroll a load-more callback wired up you're building a paginated/infinite list
useResizeObserver a callback on size change the element's size matters, not its visibility
useElementSize
{ width, height } as state
you just need live width/height
useElementBounding the full bounding rect you need viewport-relative position (changes on scroll)


For the full tour of how these compose, see React Observer Hooks: 7 Ways to Watch the DOM.






Takeaways




  • A scroll listener plus getBoundingClientRect() is the wrong tool for "is this on screen" — it thrashes the main thread and still misses scroll containers. IntersectionObserver answers it correctly, batched and off the scroll path.


  • useIntersectionObserver(target, callback, options?) wires it into React: hand it a ref, a callback that receives the raw entries, and the native options. It returns a stop() and auto-disconnects on unmount.

  • It's callback-based on purpose — you decide what "visible" means via entry.isIntersecting / entry.intersectionRatio. The callback is never stale, so it reads fresh props every time it fires.

  • Call stop() inside the callback for one-shot jobs (lazy-load, fire-once analytics); skip it for repeating triggers (infinite scroll).

  • Tune with threshold (how much must show), rootMargin (fire early/late), and root (measure against a container, not the viewport).

  • Want just a boolean? useElementVisibility returns [isVisible, stop]. Both are SSR-safe.



Grab it from @reactuses/core and delete your scroll-listener boilerplate.

Information ergänzen Fachhinweis, Update, Korrektur oder Quelle zur Meldung beitragen
Gäste-Hinweise werden kurz redaktionell geprüft und danach hier angezeigt.

Community-Hinweise zur Meldung

0 freigegeben
Social ReaktionenReagiere als Erste:r — dein Feedback zählt!
Informations-Bewertung:

💬 Discussion communautaire et commentaires

🌐 Rejoindre le chat principal

Lancez la discussion dans le flux diffusé du Social Chat ou proposez ci-dessus une contribution experte via le formulaire de complément.

Évaluation communautaire &amp; preuve sociale
⭐ Avis des lecteurs
–
Ø / 5.0
Pas encore d'évaluation des lecteurs
Cet article vous a-t-il été utile ?
0
Donner votre évaluation
Évaluation détaillée (facultatif)
Contenu & qualité
Source & fiabilité
Actualité
Briefing sécurité Gratuit · désabonnement en 1 clic

Intelligence Digest — gratuit

Chaque jour, les principales actualités sécurité · résiliable à tout moment

Groupes d’histoires apparentées & sources (IA vectorielle)

6 Cluster
26 sources
ForgeOS Booted on a Real Server: Linux Kernel Below, Only Our Own Code Above
DEV Community il y a 1 h
25 autres sources
VulDB Updatesil y a 2 hCVE-2026-72239 | Linux Kernel sev x86/virt/sev/sev.c wbinvd_on_all_cpus state issue (WID-SEC-2026-2852) VulDB Updatesil y a 2 hCVE-2026-72240 | Linux Kernel up to 7.1.4 mfd sm501_register_device memory leak (WID-SEC-2026-2852) VulDB Updatesil y a 2 hCVE-2026-72241 | Linux Kernel up to 7.1.4 uleds strchr buffer overflow (WID-SEC-2026-2852) VulDB Updatesil y a 2 hCVE-2026-72244 | Linux Kernel up to 6.12.100/6.18.41/7.1.4/7.2-rc2 gpu-buddy allocation of resources (WID-SEC-2026-2852) VulDB Updatesil y a 2 hCVE-2026-72243 | Linux Kernel up to 7.2-rc2 selinux socket_sendmsg permission (Nessus ID 364200 / WID-SEC-2026-2852) VulDB Updatesil y a 2 hCVE-2026-72245 | Linux Kernel up to 7.1.4 host1x host1x_device_parse_dt release of resource (WID-SEC-2026-2852) VulDB Updatesil y a 2 hCVE-2026-72246 | Linux Kernel flowtable input validation (WID-SEC-2026-2852) VulDB Updatesil y a 2 hCVE-2026-72247 | Linux Kernel up to 7.2-rc3 nf_conncount __nf_conncount_add dir comparison (WID-SEC-2026-2852) VulDB Updatesil y a 2 hCVE-2026-72248 | Linux Kernel up to 7.1.4/7.2-rc2 flowtable nft_flow_dst_release buffer overflow (WID-SEC-2026-2852) LinuxAndUbuntuil y a 2 hLinux AutoFDO Benchmark: Clang Kernel Optimization FOSS Linuxil y a 2 hNFS2ROOT: Pre-Auth Flaw in the Linux NFS Server VulDB Updatesil y a 3 hCVE-2022-31607 | NVIDIA GPU Display Driver on Linux Kernel Mode Layer nvidia.ko input validation (EUVD-2022-53059 / Nessus ID 339047) VulDB Updatesil y a 4 hCVE-2026-72227 | Linux Kernel up to 6.12.96/6.18.39/7.1.4/7.2-rc2 batman-adv out-of-bounds (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72228 | Linux Kernel up to 7.2-rc2 batman-adv skb_split memory leak (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72229 | Linux Kernel up to 7.2-rc2 batman-adv register_netdevice memory leak (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72231 | Linux Kernel up to 7.2-rc2 batman-adv batadv_send_tt_request allocation of resources (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72230 | Linux Kernel up to 7.2-rc2 batman-adv batadv_frag_send_packet memory leak (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72232 | Linux Kernel up to 7.2-rc2 batman-adv batadv_interface_tx out-of-bounds (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72234 | Linux Kernel up to 7.2-rc1 batman-adv batadv_get_vid use after free (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72233 | Linux Kernel up to 7.2-rc1 batman-adv batadv_bla_is_backbone_gw use after free (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72236 | Linux Kernel up to 7.2-rc3 s390/perf_cpum_cf __hw_perf_event_init config array index (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72235 | Linux Kernel up to 7.2-rc1 batman-adv batadv_interface_rx use after free (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72237 | Linux Kernel up to 7.2-rc2 BRS /x86/amd/brs amd_brs_match_plm information disclosure (WID-SEC-2026-2852) VulDB Updatesil y a 4 hCVE-2026-72238 | Linux Kernel up to 7.2-rc3 x86 boot early_serial_init integer overflow (WID-SEC-2026-2852) DEV Communityil y a 4 hIs that GPTBot real? How to verify Googlebot, Bingbot and AI crawlers in your server logs
14 sources
Amazon Australia Cyber Monday deals
Latest from TechRadar il y a 33 min.
13 autres sources
CNETil y a 43 min.This Pocket Battery Recharges Your Phone 4 Times, and it’s Only $38 for Cyber Monday Latest from TechRadaril y a 1 hFirebat's M1 is a cracking Ryzen AI 9 HX 470 mini PC for AI workloads — and it's packing OCuLink, 32GB of RAM, and a 1TB SSD for $1020 this Cyber Monday Latest from TechRadaril y a 1 hThe Lenovo IdeaCentre Tower Copilot+ PC with Core Ultra 7 CPU isn't discounted for Cyber Monday — and it's still the desktop computer I'd buy for work for $1049 The Vergeil y a 1 hQobuz is my streaming service of choice and it’s on sale during Cyber Monday CNETil y a 12 joursThis Paramount Plus Cyber Monday Deal Gets You Ad-Free Viewing for Only $3 Per Month CNETil y a 1 hCyber Monday Meta Quest 3S Deal Knocks $53 Off and Gets You $50 Free Amazon Credit WIREDil y a 4 hThe 31+ Very Best Amazon Black Friday Deals (2026): Up to 50% Off The Vergeil y a 2 hThese early Cyber Monday gaming laptop deals offer the most GPU for the least money Latest from TechRadaril y a 3 hGrab a TP-Link dual-band Wi-Fi 6 router with 1.5Gbps for $44 this Cyber Monday CNETil y a 4 hUpgrade Your Emergency Preparedness Kit With Black Friday and Cyber Monday Deals on Power Stations, Flashlights, Solar and More AppleInsider Newsil y a 4 hAirPods Max 2 plunge to best $399 price with $150 Cyber Monday discount Latest from TechRadaril y a 4 hI test Apple TV VPNs for a living — here are the 3 VPNs worth your money for Black Friday and Cyber Monday WIREDil y a 4 hCyber Monday Deals, Curated Live By Our Experts (2026)
Articles similaires
🔍 Verwandte News

Auch interessante Nachrichten React useIntersectionObserver Hook: Lazy Load & Detect Visibility (2026)

Thematisch verwandte Begriffe: React, useIntersectionObserver, Hook, Lazy · 6 Treffer

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

💬 Chargement des commentaires…
Sentinel CTI: ONLINE
Tirer pour actualiser
Widgets & sujets
Chargement des widgets…
Article suivant