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

推荐订阅源

Project Zero
Project Zero
Security Archives - TechRepublic
Security Archives - TechRepublic
C
Cyber Attacks, Cyber Crime and Cyber Security
Security Latest
Security Latest
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Vulnerabilities – Threatpost
C
CERT Recently Published Vulnerability Notes
S
Schneier on Security
G
GRAHAM CLULEY
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
I
Intezer
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
F
Full Disclosure
T
The Exploit Database - CXSecurity.com
P
Proofpoint News Feed
WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
H
Help Net Security
大猫的无限游戏
大猫的无限游戏
MyScale Blog
MyScale Blog
Hacker News: Ask HN
Hacker News: Ask HN
G
Google Developers Blog
H
Heimdal Security Blog
O
OpenAI News
Hugging Face - Blog
Hugging Face - Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
L
LangChain Blog
C
Cisco Blogs
云风的 BLOG
云风的 BLOG
IT之家
IT之家
Cyberwarzone
Cyberwarzone
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Know Your Adversary
Know Your Adversary
博客园 - 聂微东
The Cloudflare Blog
C
Check Point Blog
K
Kaspersky official blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
月光博客
月光博客
T
Tor Project blog
T
Threat Research - Cisco Blogs
T
Tailwind CSS Blog
P
Proofpoint News Feed
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
A
About on SuperTechFans
小众软件
小众软件
Cloudbric
Cloudbric
A
Arctic Wolf

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
Demystifying the Browser Render Cycle: useLayoutEffect, requestAnimationFrame, and Layout Thrashing
Kapil Thukra · 2026-05-17 · via DEV Community

As React developers, we often live in a comfortable world of state, props, and virtual DOMs. React handles the heavy lifting of updating the UI, and we rarely have to think about how pixels actually hit the glass.

However, when you need to build high-performance animations, drag-and-drop interfaces, or perfectly positioned tooltips, the abstraction leaks. You suddenly find yourself staring at weird UI flashes, dropped frames, or laggy layouts.

To fix these issues, you have to master three things: the Browser Render Cycle, React’s useLayoutEffect, and the native requestAnimationFrame API.

In this deep dive, we will map out exactly how these pieces fit together, explore the mechanics of Layout Thrashing, and learn how to write buttery-smooth UI code.


1. The Anatomy of a Single Browser Frame

To understand why our code can slow down a website, we first need to look at the browser's daily routine. Modern screens refresh 60 to 120 times per second. That means for a 60Hz monitor, the browser has exactly 16.6 milliseconds to process code and redraw the screen for a single frame.

When a piece of JavaScript alters something on a webpage, it kicks off a strict, linear pipeline called the Browser Critical Rendering Path.

  1. JavaScript: JavaScript executes and mutates the DOM tree structure or changes CSS classes.
  2. Style (Recalculate Styles): The browser matches CSS selectors against the new DOM structure to figure out which rules apply to which elements.
  3. Layout (Reflow): The browser calculates the geometry of the page. It figures out exactly how many pixels wide an element is, where it sits relative to its parent, and how it impacts surrounding elements.
  4. Paint: The browser fills in the pixels. It draws backgrounds, text colors, borders, shadows, and images. This happens across multiple separate "layers" in memory.
  5. Composite: The browser takes all those separate layers, layers them in the correct $Z$-index order, and sends them to the GPU to be drawn onto your monitor.

2. Where React and the Event Loop Fit In

When you write React code, your component updates run inside the JavaScript phase of the Event Loop. However, the Event Loop handles different types of code execution using distinct queues.

Let's look at the absolute chronological timeline of a single frame execution when a React state change occurs:

Phase A: The Execution Window

  • Macrotask Execution: The loop picks up a standard task (like a user clicking a button).
  • The Microtask Flush: As soon as that task finishes, the browser pauses everything to empty the Microtask Queue. This is where React’s Render and Commit phases live. React updates its internal state, calculates the virtual DOM, and writes the new nodes to the real DOM.

Phase B: The useLayoutEffect Interrupt

  • Because useLayoutEffect is synchronous, it fires immediately after React writes to the real DOM, but inside this same JavaScript execution window. The browser's layout and paint steps have not happened yet.

Phase C: The Render Pipeline

Once all JavaScript and microtasks are completely finished, the browser thread takes control to prepare the visual frame:

  • requestAnimationFrame (rAF): The browser executes any queued rAF callbacks. This is the last chance for JavaScript to run right before the browser calculates geometry.
  • Style & Layout: The browser calculates the positions and sizes of the elements.
  • Paint & Composite: Pixels hit the screen.

Phase D: The Post-Paint Window

  • useEffect Fires: Now that the user is looking at the updated screen, React asynchronously shoots off your standard useEffect hooks in the background so they don't block visual performance.

3. The Showdown: useLayoutEffect vs requestAnimationFrame

Both tools are used to synchronize code with the display, but they serve completely different masters.

Feature useLayoutEffect requestAnimationFrame (rAF)
Ecosystem React-specific hook. Native Browser Web API.
Execution Timing Post-DOM mutation, Pre-Paint (Microtask window). Right before the browser's native Style/Layout steps.
Blocking Behavior Synchronous. Halts the browser from printing pixels until it finishes. Asynchronous. Runs inside the browser's natural frame pacing.
Primary Use Case Fixing visual flickers by measuring/adjusting layout before rendering. High-performance, continuous UI animations and transitions.

The "Next Frame" Catch with rAF

If you schedule a requestAnimationFrame inside a standard event listener, it runs in that same frame's pipeline.

However, if you schedule a rAF inside useLayoutEffect, you are calling it at a very late stage in the JavaScript window. The browser has already locked in its pipeline plan for the current frame. As a result, the rAF callback is pushed to the next frame.

If you use rAF to change styles inside useLayoutEffect, the user will see the unadjusted layout for exactly one frame (a visual flicker) before the rAF updates the styles on the next frame.


4. Understanding Layout Thrashing

To optimize animations, you must avoid the silent performance killer: Layout Thrashing.

By default, the browser is incredibly lazy—and that's a good thing. When you write code like this:

div1.style.width = '200px';
div2.style.height = '300px';

Enter fullscreen mode Exit fullscreen mode

The browser doesn't calculate the layout twice. It simply marks its current layout data structure as "dirty". It waits until all your JavaScript code is done, and then performs a single, optimized Layout calculation right before painting.

What is Forced Synchronous Layout?

Layout Thrashing happens when you force the browser to perform this layout calculation over and over again inside a single block of JavaScript code. This occurs when you Write a style change, and then immediately Read a layout property.

Consider this code running inside a hook:

// ❌ LAYOUT THRASHING
const w1 = element1.offsetWidth;       // 1. Browser layout is clean, returns value instantly.
element1.style.width = (w1 + 10) + 'px'; // 2. DOM is mutated. Layout is now marked "DIRTY".

const w2 = element2.offsetWidth;       // 3. BOOM! Browser needs to return an accurate number,
                                        //    but layout is dirty. It is FORCED to pause your JS 
                                        //    and run an emergency, synchronous Layout calculation.
element2.style.width = (w2 + 10) + 'px'; // 4. Layout is marked dirty AGAIN.

Enter fullscreen mode Exit fullscreen mode

If you repeat this pattern inside a loop or across multiple components, you force the browser to compute the geometry of the entire webpage multiple times in a few milliseconds. This ruins your 16.6ms frame budget, causing severe animation lag (jank).


5. Why Reading Values in useLayoutEffect Causes Thrashing

When React executes your components, it processes them sequentially. If multiple child components contain useLayoutEffect hooks that individually read geometry and write style changes, they will trigger layout thrashing automatically.

// Component A (Child 1)
useLayoutEffect(() => {
  const width = boxRef.current.offsetWidth; // Read (Layout clean)
  boxRef.current.style.left = `${width}px`;  // Write (Layout becomes DIRTY)
}, []);

// Component B (Child 2)
useLayoutEffect(() => {
  const height = menuRef.current.offsetHeight; // Read (CRITICAL: Layout is dirty! Forces Reflow)
  menuRef.current.style.top = `${height}px`;    // Write (Layout becomes dirty again)
}, []);

Enter fullscreen mode Exit fullscreen mode

Because useLayoutEffect runs synchronously right after React commits updates, the second component attempts to read from a DOM tree that was just marked "dirty" by the first component. The browser has no choice but to halt execution and perform an emergency reflow.


6. How to Avoid Layout Thrashing

The golden rule for maintaining smooth frame rates is simple: Batch your reads first, and batch your writes last.

The Correct useLayoutEffect Pattern (For Instant Adjustments)

If you need to adjust positioning before an element appears on screen to prevent a flicker, keep all reads together at the top of your effect, and apply your writes at the very end.

//  PERFECTLY BATCHED
useLayoutEffect(() => {
  // 1. Do all READS first while layout is clean
  const width1 = div1.offsetWidth;
  const width2 = div2.offsetWidth;

  // 2. Do all WRITES at the end
  div1.style.transform = `translateX(${width1}px)`;
  div2.style.transform = `translateX(${width2}px)`;
}, []);

Enter fullscreen mode Exit fullscreen mode

The Hybrid Pattern (For Kicking off Smooth Animations)

If you are measuring an element to kick off a fluid, moving animation where a 1-frame delay is acceptable, you can read inside useLayoutEffect and defer the write to requestAnimationFrame.

This unblocks React's render phase completely and hands the styling work directly to the browser's native animation loop:

// ⚡ OPTIMIZED FOR ANIMATIONS
useLayoutEffect(() => {
  // Read when the layout is clean
  const currentHeight = elementRef.current.offsetHeight;

  // Defer the write to the browser's native animation timeline
  const frameId = requestAnimationFrame(() => {
    elementRef.current.style.height = `${currentHeight + 100}px`;
    elementRef.current.style.transition = 'height 300ms ease';
  });

  return () => cancelAnimationFrame(frameId);
}, []);

Enter fullscreen mode Exit fullscreen mode

By respecting the browser’s render pipeline and keeping your reads and writes separated, you ensure your React applications remain highly responsive and visually seamless.


Usecase: Positioning a tooltip around button

To position a tooltip perfectly relative to a target element (like a button), you must use useLayoutEffect.

If you use standard useEffect, the tooltip will render briefly at a default position (e.g., top-left corner or stacked awkwardly in the DOM) before jumping to the correct coordinates, causing a jarring visual flash.

useLayoutEffect lets you measure the button, calculate the math, and place the tooltip before the browser paints the screen, making the appearance completely seamless.

Here is a complete, production-ready example of how to implement this without causing layout thrashing:

import React, { useState, useLayoutEffect, useRef } from 'react';

function TooltipButton() {
  const [showTooltip, setShowTooltip] = useState(false);

  // Refs to target the real DOM elements
  const buttonRef = useRef(null);
  const tooltipRef = useRef(null);

  useLayoutEffect(() => {
    // If the tooltip isn't open, there is nothing to measure
    if (!showTooltip || !buttonRef.current || !tooltipRef.current) return;

    const button = buttonRef.current;
    const tooltip = tooltipRef.current;

    // --- STEP 1: BATCHED READS (Layout is clean) ---
    // Get the bounding boxes of both elements from browser memory
    const buttonRect = button.getBoundingClientRect();
    const tooltipRect = tooltip.getBoundingClientRect();

    // --- STEP 2: CALCULATE MATH (Pure JS calculation) ---
    // Position the tooltip directly above the center of the button
    const topPosition = buttonRect.top - tooltipRect.height - 8; // 8px spacing
    const leftPosition = buttonRect.left + (buttonRect.width / 2) - (tooltipRect.width / 2);

    // --- STEP 3: BATCHED WRITES (Layout becomes dirty) ---
    // Apply styles directly to the DOM nodes right before the browser paints
    tooltip.style.top = `${topPosition + window.scrollY}px`;
    tooltip.style.left = `${leftPosition + window.scrollX}px`;

  }, [showTooltip]); // Re-run calculations whenever the tooltip is toggled open

  return (
    <div style={{ padding: '100px', textAlign: 'center' }}>
      <button 
        ref={buttonRef}
        onMouseEnter={() => setShowTooltip(true)}
        onMouseLeave={() => setShowTooltip(false)}
        className="trigger-button"
      >
        Hover over me
      </button>

      {showTooltip && (
        <div 
          ref={tooltipRef} 
          className="tooltip-box"
          style={{
            position: 'absolute',
            backgroundColor: '#333',
            color: '#fff',
            padding: '8px 12px',
            borderRadius: '4px',
            fontSize: '14px',
            pointerEvents: 'none',
            whiteSpace: 'nowrap',
            // Start invisible or unpositioned so it doesn't flash 
            // if layout changes drastically
            top: 0,
            left: 0, 
          }}
        >
          Dynamic Tooltip Text!
        </div>
      )}
    </div>
  );
}

export default TooltipButton;

Enter fullscreen mode Exit fullscreen mode


Why this follows the Rules perfectly:

  1. It Prevents the Flicker: When showTooltip becomes true, React inserts the tooltip markup into the DOM. Before the browser draws it, useLayoutEffect halts the paint train.
  2. It Follows the Read-then-Write Pattern: Notice how button.getBoundingClientRect() and tooltip.getBoundingClientRect() are invoked right next to each other at the very beginning. This forces exactly one synchronous layout calculation.
  3. It Finishes with the Writes: The styles are injected at the very end. The browser receives the style modifications, closes the useLayoutEffect execution window, and proceeds to draw the tooltip exactly where it belongs on its very first visual frame.

Usecase: Update progressbar as the user scrolls through a blog

Creating a smooth, high-performance Custom Scroll Animation or a Progress Indicator that moves as the user scrolls down a page.

Handling scroll events in JavaScript is notoriously heavy. If a user scrolls quickly, the browser can fire the onScroll event up to 100 times per second. If you try to update the DOM (like modifying the width of a progress bar) on every single scroll event, you will overwhelm the browser thread, causing Layout Thrashing and severe visual stuttering ("jank").

By using requestAnimationFrame, you can decouple the rapid scroll events from the actual DOM updates, ensuring your animation code runs exactly once per browser frame.


Here is how you can use requestAnimationFrame in React to build a high-performance reading progress bar that fills up as the user scrolls down an article.

import React, { useState, useEffect, useRef } from 'react';

function ScrollProgressBar() {
  const [scrollProgress, setScrollProgress] = useState(0);

  // A ref to keep track of whether a frame has already been requested.
  // This acts as a lock mechanism to prevent spamming the browser.
  const rafTick = useRef(false);

  useEffect(() => {
    const handleScroll = () => {
      // If a frame calculation is already scheduled, ignore incoming scroll events
      if (rafTick.current) return;

      // Lock: We are now scheduling a frame update
      rafTick.current = true;

      // Schedule the visual update right before the next browser paint
      requestAnimationFrame(() => {
        const totalHeight = document.documentElement.scrollHeight - window.innerHeight;

        if (totalHeight > 0) {
          const progress = (window.scrollY / totalHeight) * 100;
          setScrollProgress(progress);
        }

        // Unlock: The frame has painted, we can accept a new scroll update now
        rafTick.current = false;
      });
    };

    // Listen to the window scroll event
    window.addEventListener('scroll', handleScroll, { passive: true });

    // Clean up the event listener on unmount
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <div>
      {/* The Progress Bar Container */}
      <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '5px',
        backgroundColor: '#e0e0e0',
        zIndex: 1000
      }}>
        {/* The Animated Filling Bar */}
        <div style={{
          height: '100%',
          width: `${scrollProgress}%`,
          backgroundColor: '#007bff',
          // Notice we don't need a CSS transition here! 
          // rAF updates fast enough to feel naturally smooth.
        }} />
      </div>

      {/* Placeholder content to make the page scrollable */}
      <div style={{ padding: '20px', lineHeight: '2' }}>
        <h1>High-Performance Scroll Tracking</h1>
        <p style={{ height: '2000px' }}>Scroll down to see the progress bar animate...</p>
      </div>
    </div>
  );
}

export default ScrollProgressBar;

Enter fullscreen mode Exit fullscreen mode


Why requestAnimationFrame is the Perfect Fit Here

  1. It Implements "Throttling" Automatically: By using the rafTick.current boolean lock, we ignore the dozens of extra scroll events fired by the browser between frames. We only compute the scroll math when the browser is actively ready to draw a new frame.
  2. Perfect Frame Alignment: If the user is running a 144Hz gaming monitor, requestAnimationFrame will naturally execute 144 times a second. If they are on a 60Hz phone, it executes 60 times a second. The animation effortlessly self-corrects to match the hardware's native refresh rate.
  3. Power Saving: If the user switches tabs or minimizes the browser, requestAnimationFrame automatically pauses itself in the background. Standard setTimeout loops or raw scroll events keep chugging along in memory, draining the device's battery unnecessarily.