Debouncing in React and Next.js

Debouncing is a powerful technique used to limit how often a function is executed, especially in response to rapid user input events like typing, scrolling, or resizing. It helps prevent unnecessary function calls, improves performance, and creates a smoother user experience.

Watch the Tutorial

Why Debouncing?

When building React or Next.js apps, you often need to handle events such as search input, window resizing, or API calls. Without debouncing, every keystroke or event can trigger a function, leading to performance bottlenecks and excessive network requests.

For example, in a search bar, you want to wait until the user stops typing before making an API call. Debouncing ensures the function only runs after a specified delay since the last event.

How Debouncing Works

Debouncing works by delaying the execution of a function until after a certain period of inactivity. If the event is triggered again before the delay ends, the timer resets.

Implementing Debouncing in React

Here's a simple debounce utility function:

debounce.js
1function debounce(fn, delay) { 2let timer; 3return (...args) => { 4 clearTimeout(timer); 5 timer = setTimeout(() => { 6 fn(...args); 7 }, delay); 8}; 9}

You can use this debounce function in a React component:

SearchInput.jsx
1import React, { useState, useCallback } from "react"; 2 3function debounce(fn, delay) { 4let timer; 5return (...args) => { 6 clearTimeout(timer); 7 timer = setTimeout(() => { 8 fn(...args); 9 }, delay); 10}; 11} 12 13export default function SearchInput() { 14const [query, setQuery] = useState(""); 15 16const handleSearch = useCallback( 17 debounce((value) => { 18 // Simulate API call 19 console.log("Searching for:", value); 20 }, 500), 21 [] 22); 23 24const handleChange = (e) => { 25 setQuery(e.target.value); 26 handleSearch(e.target.value); 27}; 28 29return ( 30 <input 31 type="text" 32 value={query} 33 onChange={handleChange} 34 placeholder="Type to search..." 35 /> 36); 37} 38

Debouncing in Next.js

Next.js is built on React, so you can use the same debouncing techniques. Debouncing is especially useful in Next.js API routes, server actions, or client-side data fetching to avoid unnecessary requests.

For example, you might debounce a search input that fetches data from a Next.js API route:

api/search.js
1// pages/api/search.js 2export default function handler(req, res) { 3const { query } = req.query; 4// Simulate search logic 5res.status(200).json({ results: }); 6}
SearchInputWithAPI.jsx
1import React, { useState, useCallback } from "react"; 2 3function debounce(fn, delay) { 4let timer; 5return (...args) => { 6 clearTimeout(timer); 7 timer = setTimeout(() => { 8 fn(...args); 9 }, delay); 10}; 11} 12 13export default function SearchInput() { 14const [query, setQuery] = useState(""); 15const [results, setResults] = useState([]); 16 17const fetchResults = useCallback( 18 debounce(async (value) => { 19 const res = await fetch(); 20 const data = await res.json(); 21 setResults(data.results); 22 }, 500), 23 [] 24); 25 26const handleChange = (e) => { 27 setQuery(e.target.value); 28 fetchResults(e.target.value); 29}; 30 31return ( 32 <div> 33 <input 34 type="text" 35 value={query} 36 onChange={handleChange} 37 placeholder="Type to search..." 38 /> 39 <ul> 40 {results.map((r, i) => ( 41 <li key={i}>{r}</li> 42 ))} 43 </ul> 44 </div> 45); 46} 47

Tips for Using Debouncing

  • Choose an appropriate delay (e.g., 300-500ms for search inputs)
  • Use useCallback to memoize debounced functions in React
  • Debounce expensive operations like API calls, filtering, or resizing
  • Consider using libraries like lodash's _.debounce for more features

Conclusion

Debouncing is essential for building performant, user-friendly React and Next.js applications. By limiting function calls and network requests, you create smoother experiences and reduce server load. Try adding debouncing to your next project and see the difference!

Logo

I'm Avinash - a full-stack developer, freelancer & problem solver. Thanks for checking out iBlogs!

Platforms
YouTube