DEV Community

Ola Abaza
Ola Abaza

Posted on • Edited on

1 RN Thing a Day – Day 2: Throttling πŸ†š Debouncing

Throttle
Limits a function to execute once every X ms.

Use Case: Limit frequency of rapievents.ts

Example Use: Scroll, resize, Location updates (e.g., GPS), button taps

Example: Scroll Event

import throttle from 'lodash/throttle';

const handleScroll = throttle((event) => {
  console.log('Scrolling...', event.nativeEvent.contentOffset.y);
}, 1000); // Only once every 1 second

<ScrollView onScroll={handleScroll} scrollEventThrottle={16} />
Enter fullscreen mode Exit fullscreen mode

πŸ” Even if the scroll event fires 60 times per second, your handler only fires once every 1000 ms.

Debounce
Waits until a function hasn't been called for X ms.

Use Case: React to the final event after user stops

Example Use: Text search, Form validation while typing, autocomplete, form

Example: Text Input

import debounce from 'lodash/debounce';

const handleChange = debounce((text) => {
  console.log('Searching for:', text);
}, 500); // Only runs 500ms after user stops typing

<TextInput onChangeText={handleChange} />
Enter fullscreen mode Exit fullscreen mode

⏳ The user types "h-e-l-l-o," and the function fires once, after the user pauses for 500 ms.

What debounce() Does Internally:

When you call:

debounce((text) => { ... }, 500)

Enter fullscreen mode Exit fullscreen mode

…it wraps your function in a way that:

  1. Every time the function is called (e.g., from onChangeText while typing),
  2. It resets a timer (using setTimeout)
  3. The actual function only runs if the timer completes without interruption (i.e., you stop typing for ms).

Utility Code Without Lodash (Optional)
You can write your own too:

function debounce(fn, delay) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
}
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Top comments (0)