惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Cyberwarzone
Cyberwarzone
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
小众软件
小众软件
Recent Announcements
Recent Announcements
博客园 - 三生石上(FineUI控件)
Security Archives - TechRepublic
Security Archives - TechRepublic
W
WeLiveSecurity
Cloudbric
Cloudbric
博客园 - 司徒正美
美团技术团队
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
PCI Perspectives
PCI Perspectives
宝玉的分享
宝玉的分享
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
Last Week in AI
Last Week in AI
S
Schneier on Security
N
News | PayPal Newsroom
B
Blog RSS Feed
L
LINUX DO - 最新话题
T
Troy Hunt's Blog
S
Secure Thoughts
雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
L
Lohrmann on Cybersecurity
G
Google Developers Blog
Microsoft Azure Blog
Microsoft Azure Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tenable Blog
S
Securelist
L
LangChain Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
I
InfoQ
H
Heimdal Security Blog
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
K
Kaspersky official blog
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
C
Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
React Observer Hooks: 7 Ways to Watch the DOM Without the Boilerplate
reactuse.com · 2026-05-13 · via DEV Community

React Observer Hooks: 7 Ways to Watch the DOM Without the Boilerplate

The DOM does not tell React when it changes. React owns one direction of the data flow — state goes in, markup comes out — and is mostly blind on the way back. If a third-party script injects a banner, if a font finishes loading and shoves the layout down 8 pixels, if a user resizes the window or scrolls a card into view, React has no idea unless you tell it. The browser ships four *Observer APIs to plug that gap, plus the getBoundingClientRect family for one-shot reads, and together they cover almost every "react to the DOM" requirement a real app has.

The trouble is that wiring observers into a React component is a small swamp of useEffect, useRef, cleanup functions, SSR guards, and the dreaded "observer fires before mount" race. Five lines of API turn into thirty lines of glue, and the glue is identical between components — so it gets copy-pasted, slightly mutated each time, and quietly accrues bugs. ReactUse ships seven focused hooks that hide the glue and give you back the API surface you actually wanted.

This post walks through all seven: what each observes, when to pick which, and what you would have written by hand if you had not picked them up.

1. useIntersectionObserver — "Is this element on screen?"

IntersectionObserver is the workhorse of modern lazy-loading. It reports when a target element crosses a threshold relative to the viewport (or a scroll container), without any of the scroll listener thrashing that the same job used to require. Lazy images, infinite scroll triggers, "viewed" tracking for analytics, fade-in on enter — all built on top of it.

The Manual Way

import { useEffect, useRef, useState } from "react";

function ManualOnScreen({ 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);
      },
      { rootMargin: "0px", threshold: 0.1 },
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

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

Enter fullscreen mode Exit fullscreen mode

This works, and the moment you need a second lazy section you copy it. By component number five you have five subtly different observers, three of them with the wrong threshold, one of them leaking because somebody refactored the cleanup. The shape is right; the repetition is not.

The ReactUse Way

useIntersectionObserver takes the ref and the options, and returns whether the element is currently intersecting:

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

function OnScreen({ children }: { children: React.ReactNode }) {
  const ref = useRef<HTMLDivElement>(null);
  const isVisible = useIntersectionObserver(ref, {
    threshold: 0.1,
  });

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

Enter fullscreen mode Exit fullscreen mode

The hook owns the observer's lifecycle: it disconnects on unmount, recreates the observer when the options change, and is SSR-safe. Lazy-load an image, fire an analytics event the first time a card enters the viewport, or defer mounting a heavy chart until it scrolls in — same hook, different boolean.

A common pattern is the "load more" trigger for infinite scroll: place a sentinel <div> at the bottom of a list and fire the fetch when it becomes visible. That is essentially the implementation of useInfiniteScroll, which builds on this primitive.

2. useElementVisibility — The Boolean You Usually Want

A surprising amount of the time you do not care about IntersectionObserverEntry at all — you just want a boolean, and you want it for the whole viewport, not a scroll container. useElementVisibility is exactly that.

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

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

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

Enter fullscreen mode Exit fullscreen mode

Use it for fade-in-on-scroll, "viewed" telemetry, and "pause this video when it scrolls off-screen" patterns. When you need finer control — a custom root, a threshold below 1, multiple thresholds — drop down to useIntersectionObserver.

3. useResizeObserver — The Right Way to Track Size

For about a decade, "track an element's size in React" meant attaching a window.resize listener and re-reading clientWidth on every event. That misses the most common case — the element resizing because its parent did, or because a sibling collapsed, or because a flex item below it grew. ResizeObserver fires on any size change to the observed element, regardless of cause.

The Manual Way

import { useEffect, useRef, useState } from "react";

function ManualSize() {
  const ref = useRef<HTMLDivElement>(null);
  const [size, setSize] = useState({ width: 0, height: 0 });

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const ro = new ResizeObserver((entries) => {
      const cr = entries[0].contentRect;
      setSize({ width: cr.width, height: cr.height });
    });
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  return (
    <div ref={ref}>
      {size.width.toFixed(0)} × {size.height.toFixed(0)}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

The hidden cost: every entry update calls setState, which schedules a render. Resize a parent quickly and the observed component re-renders 60 times a second. Most of the time you can live with this, but if the state is consumed by an expensive subtree you need to either throttle the updates or push them into a ref instead.

The ReactUse Way

useResizeObserver accepts the ref and a callback that fires on each entry:

import { useRef, useState } from "react";
import { useResizeObserver } from "@reactuses/core";

function ResponsiveCard() {
  const ref = useRef<HTMLDivElement>(null);
  const [variant, setVariant] = useState<"narrow" | "wide">("narrow");

  useResizeObserver(ref, ([entry]) => {
    setVariant(entry.contentRect.width > 600 ? "wide" : "narrow");
  });

  return <div ref={ref} data-variant={variant}></div>;
}

Enter fullscreen mode Exit fullscreen mode

This is the container-query pattern in fifteen lines: the card swaps between a narrow and a wide layout based on its own width, not the viewport's. Place two of them in a flex row and they each pick their own layout independently.

4. useElementSize and useMeasure — Size in Two Flavors

If you only need width and height, the callback form is overkill. ReactUse ships two convenience hooks that wrap ResizeObserver and return state directly.

useElementSize returns { width, height } for the observed element:

import { useRef } from "react";
import { useElementSize } from "@reactuses/core";

function AutoFitGrid({ items }: { items: Item[] }) {
  const ref = useRef<HTMLDivElement>(null);
  const { width } = useElementSize(ref);
  const columns = Math.max(1, Math.floor(width / 240));

  return (
    <div
      ref={ref}
      style={{
        display: "grid",
        gridTemplateColumns: `repeat(${columns}, 1fr)`,
        gap: 16,
      }}
    >
      {items.map((it) => <Card key={it.id} item={it} />)}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

The grid recomputes its column count whenever the container resizes — no media queries, no viewport guess, no JavaScript-controlled CSS variables.

useMeasure returns the full ResizeObserverEntry.contentRect (width, height, top, left, etc.) plus a ref to attach. Use it when you want size and the local coordinates in one call:

import { useMeasure } from "@reactuses/core";

function TooltipAnchor() {
  const [ref, rect] = useMeasure<HTMLButtonElement>();
  return (
    <>
      <button ref={ref}>Hover me</button>
      <Tooltip x={rect.left + rect.width / 2} y={rect.top} />
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

The split between useElementSize and useMeasure is mostly ergonomic — pick whichever returns the shape your component already wants to consume.

5. useElementBounding — Position Plus Size, Synced

useElementBounding is the reactive equivalent of calling el.getBoundingClientRect() on every scroll and resize. It returns top, right, bottom, left, width, height, x, y — the full rect — and re-fires when the element moves or resizes for any reason.

import { useRef } from "react";
import { useElementBounding } from "@reactuses/core";

function StickyShadow() {
  const ref = useRef<HTMLDivElement>(null);
  const { top } = useElementBounding(ref);
  const stuck = top <= 0;

  return (
    <header
      ref={ref}
      className={stuck ? "header header--stuck" : "header"}
    ></header>
  );
}

Enter fullscreen mode Exit fullscreen mode

When a position: sticky header reaches the top of the viewport, its top becomes 0; the hook picks that up and the header gets a shadow. The same pattern works for floating action buttons that should change appearance once they leave their initial position, or popovers that need to track an anchor through layout changes.

The difference between useElementBounding and useMeasure: bounding is the viewport-relative rect (it changes on scroll), measure is the element's intrinsic content rect (it does not). Pick bounding when you care about position, measure when you care about size.

6. useMutationObserver — When the DOM Changes Around You

MutationObserver is the heaviest of the four observer APIs, and the one with the narrowest legitimate use case. It fires when attributes, child nodes, or text content change on a target. In a React-first app you almost never need it — React owns the mutations, so React knows them. You reach for useMutationObserver when something outside React is mutating the DOM:

  • A third-party widget (Stripe Elements, an embedded video player, a chat bubble) injects content into a slot.
  • A contentEditable element is being edited by the user, and you want to react to text changes without polling.
  • A scripts toggles aria-expanded or data-state on an element you do not control, and you want to mirror it into React state.
import { useRef, useState } from "react";
import { useMutationObserver } from "@reactuses/core";

function ThirdPartyMount({ slot }: { slot: string }) {
  const ref = useRef<HTMLDivElement>(null);
  const [ready, setReady] = useState(false);

  useMutationObserver(
    ref,
    (mutations) => {
      const injected = mutations.some(
        (m) => m.type === "childList" && m.addedNodes.length > 0,
      );
      if (injected) setReady(true);
    },
    { childList: true, subtree: true },
  );

  return (
    <div ref={ref} data-third-party={slot}>
      {!ready && <Skeleton />}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

The skeleton renders until the third-party script drops its content into the slot, then disappears. Without MutationObserver, your options were setInterval polling or MutationObserver plus a hand-rolled lifecycle — the former is wasteful, the latter is exactly what this hook saves you from.

A common pitfall: MutationObserver is fast but not free, and an unscoped subtree watcher on a busy element can fire dozens of times per second. Always pass the narrowest options object you can — if you only care about childList, do not pass attributes: true.

7. Choosing Between Them

The seven hooks overlap, and the overlap is intentional — different shapes work for different consumers. The cheat sheet:

You want… Hook
A boolean for "is this on screen?" useElementVisibility
Visibility with a custom root or threshold useIntersectionObserver
Width and height as state useElementSize
The full content rect as state useMeasure
The viewport-relative rect (changes on scroll) useElementBounding
A callback on every resize entry useResizeObserver
To react to DOM changes from outside React useMutationObserver

A useful mental model: visibility hooks tell you where an element is relative to the user; size and bounding hooks tell you how big it is and where in the layout; mutation tells you what changed inside it.

A Worked Example: A Self-Sizing Lazy Card

Putting four of them together — a card that lazy-mounts its expensive chart only after it scrolls in, picks a layout based on its own width, and positions a tooltip relative to itself:

import { useRef, useState } from "react";
import {
  useElementVisibility,
  useElementSize,
  useElementBounding,
} from "@reactuses/core";

function LazyChartCard({ data }: { data: ChartData }) {
  const cardRef = useRef<HTMLDivElement>(null);
  const visible = useElementVisibility(cardRef);
  const { width } = useElementSize(cardRef);
  const { top, left } = useElementBounding(cardRef);

  const [hovered, setHovered] = useState(false);
  const layout = width > 600 ? "horizontal" : "vertical";

  return (
    <>
      <div
        ref={cardRef}
        data-layout={layout}
        className="card"
        onMouseEnter={() => setHovered(true)}
        onMouseLeave={() => setHovered(false)}
      >
        {visible ? <Chart data={data} /> : <Skeleton />}
      </div>
      {hovered && (
        <Tooltip
          x={left + width / 2}
          y={top - 8}
          text={`${data.label}: ${data.value}`}
        />
      )}
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

The chart only constructs once it enters the viewport. The card flips its layout based on its own width, not the page's. The tooltip floats above the card by tracking its bounding rect, so it stays anchored through scrolls and layout shifts. Three hooks, twenty lines of glue, zero useEffect blocks, zero addEventListener/removeEventListener pairs.

Performance Notes

Observers are not free, but the cost is concentrated and well-understood:

  • One observer per element is fine; one per row of a thousand-row list is not. For list virtualization, observe the scroll container once and resolve which row is visible inside the callback. The browser will sometimes coalesce many IntersectionObserver targets, but a long list with per-row observers still hurts.
  • useResizeObserver callbacks run on a separate task. Reading layout (getBoundingClientRect, offsetWidth) inside the callback is cheap; writing layout is also fine, with the catch that the write can trigger another resize entry. Guard against feedback loops by debouncing or by writing into a requestAnimationFrame.
  • MutationObserver is the most expensive of the four, especially with subtree: true. Scope it as narrowly as possible. If you find yourself watching a large subtree, consider whether a single explicit "third-party-ready" event from the embedded code would be cheaper.

Summary

The observer APIs are the bridge between "what React knows" and "what the DOM actually does." Wired with raw useEffect they accumulate a lot of glue and a long tail of subtle bugs. Wired with these seven hooks they become one-liners that compose freely.

Browse the rest at reactuse.com — and if you replace a chunky useEffect-plus-observer dance with one of these, that is a good day at the keyboard.