DEV Community

Cover image for Debouncing and Throttling in React and Angular: Code Examples
Mridu Dixit
Mridu Dixit

Posted on

Debouncing and Throttling in React and Angular: Code Examples

When building modern web apps, performance matters. Typing in a search bar, resizing a window, or scrolling a page can trigger hundreds of events per second. If each event runs expensive logic (like an API call), your app slows down.

That’s where Debouncing and Throttling come in β€” two techniques to control event execution frequency.

⏱ Debouncing

Debouncing ensures a function runs only after a certain amount of time has passed since the last event.

πŸ‘‰ Use Case: Search input (API should trigger only after the user stops typing).

βœ… React Example: Debounce with useEffect

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

function SearchBox() {
  const [query, setQuery] = useState("");

  useEffect(() => {
    const handler = setTimeout(() => {
      if (query) {
        console.log("API call with:", query);
      }
    }, 500); // wait 500ms after last keystroke

    return () => clearTimeout(handler);
  }, [query]);

  return <input onChange={(e) => setQuery(e.target.value)} />;
}

Enter fullscreen mode Exit fullscreen mode

βœ… Angular Example: Debounce with RxJS

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'app-search',
  template: `<input [formControl]="searchControl" />`
})
export class SearchComponent {
  searchControl = new FormControl();

  constructor() {
    this.searchControl.valueChanges
      .pipe(debounceTime(500)) // wait 500ms
      .subscribe(value => console.log("API call with:", value));
  }
}

Enter fullscreen mode Exit fullscreen mode

⚑ Throttling

Throttling ensures a function runs at most once in a given time interval.

πŸ‘‰ Use Case: Window resize or scroll events.

βœ… React Example: Throttle Scroll

import React, { useEffect } from "react";

function ScrollTracker() {
  useEffect(() => {
    const handleScroll = () => {
      console.log("Scroll position:", window.scrollY);
    };

    const throttled = throttle(handleScroll, 1000);

    window.addEventListener("scroll", throttled);
    return () => window.removeEventListener("scroll", throttled);
  }, []);

  const throttle = (fn, limit) => {
    let inThrottle;
    return function (...args) {
      if (!inThrottle) {
        fn(...args);
        inThrottle = true;
        setTimeout(() => (inThrottle = false), limit);
      }
    };
  };

  return <h2>Scroll the page!</h2>;
}

Enter fullscreen mode Exit fullscreen mode

βœ… Angular Example: Throttle with RxJS

import { Component, HostListener } from '@angular/core';
import { fromEvent } from 'rxjs';
import { throttleTime } from 'rxjs/operators';

@Component({
  selector: 'app-scroll-tracker',
  template: `<h2>Scroll the page!</h2>`
})
export class ScrollTrackerComponent {
  ngOnInit() {
    fromEvent(window, 'scroll')
      .pipe(throttleTime(1000)) // execute every 1s
      .subscribe(() => {
        console.log("Scroll position:", window.scrollY);
      });
  }
}

Enter fullscreen mode Exit fullscreen mode

πŸ“Š Debounce vs Throttle

Feature Debounce Throttle
Execution After inactivity At regular intervals
Use Cases Search, autocomplete, resize end Scroll, resize, mouse move

βœ… Conclusion

  • Use Debouncing when you want to wait until a user stops performing an action.
  • Use Throttling when you want to limit how often something executes during continuous actions.

Both techniques are essential for smooth, performant apps in React and Angular.

Top comments (0)