What are Debouncing and Throttling?
Imagine you’re in a room where someone keeps switching the light on and off rapidly. It’s disorienting, right? Similarly, in the digital realm, events can flood our system. We need a way to manage them:
Debouncing: Imagine telling that person, “Hey, wait a few seconds after the last time you flick the switch, then turn the light on.” That’s debouncing! It ensures a function doesn’t run immediately but waits for a brief pause in events before executing.
Throttling: Now, imagine saying, “You can only flick the switch once every 10 seconds, no matter how many times you try.” That’s throttling! It limits the function to run only once in a set time frame.
Debouncing in React:
When users type in a search bar, you might not want to start searching instantly with every keystroke. Instead, you’d prefer to wait until they’ve paused or finished typing. This improves performance and reduces unnecessary requests. Here’s how you can achieve this:
import { useState, useEffect } from 'react';
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
function SearchBar({ onSearchTermChange }) {
const [term, setTerm] = useState('');
const debouncedSearchTerm = useDebounce(term, 500);
useEffect(() => {
if (debouncedSearchTerm) {
onSearchTermChange(debouncedSearchTerm);
}
}, [debouncedSearchTerm, onSearchTermChange]);
return (
<input
value={term}
onChange={(e) => setTerm(e.target.value)}
/>
);
}
With this setup, our search will only activate after the user has stopped typing for 500 milliseconds.
Throttling in React:
When users scroll a webpage, many events fire up. Instead of responding to every single scroll event, you might want to take action just once in a while. That’s where throttling comes in:
import { useState, useEffect, useRef } from 'react';
function useThrottle(value, limit) {
const [throttledValue, setThrottledValue] = useState(value);
const lastRan = useRef(Date.now());
useEffect(() => {
const handler = setTimeout(function() {
if (Date.now() - lastRan.current >= limit) {
setThrottledValue(value);
lastRan.current = Date.now();
}
}, limit - (Date.now() - lastRan.current));
return () => {
clearTimeout(handler);
};
}, [value, limit]);
return throttledValue;
}
function SearchBar({ onSearchTermChange }) {
const [term, setTerm] = useState('');
const throttledSearchTerm = useThrottle(term, 500);
useEffect(() => {
if (throttledSearchTerm) {
onSearchTermChange(throttledSearchTerm);
}
}, [throttledSearchTerm, onSearchTermChange]);
return (
<input
value={term}
onChange={(e) => setTerm(e.target.value)}
/>
);
}
Here, our search will only updates and limiting after the user has stopped typing for 500 milliseconds.
Wrapping up:
Debouncing and throttling are essential tools in a React developer’s toolkit. They help in striking a balance between being responsive to user actions and ensuring optimal performance. Whether you’re building a dynamic search input or a smooth-scrolling experience, remember these techniques to keep your applications snappy and efficient!
Top comments (0)