3 min read
It doesn't work?
Posted byThức Trần
In this short blog, you'll know how to use debounce lodash in React or Next.js applications.
When handling user input in React, especially in scenarios like search bars or real-time form validation, it's common to run a function every time the user types. However, this can lead to excessive function executions, causing performance issues and unnecessary re-renders.
This is where debouncing comes in. Debounce is a technique that delays the execution of a function until after a specified period of inactivity. Instead of calling the function on every keystroke, it ensures that the function runs only after the user has stopped typing for a certain duration. This improves performance by reducing redundant computations and network requests.
When working with React, optimizing performance is crucial—especially when dealing with expensive computations or event handlers like debounced inputs. A common mistake developers make is calling debounce inside a component without memoization, leading to function re-creation on every render. This can cause unexpected behavior and performance issues.
In this article, we’ll explore why is often used with useMemo, how it helps optimize function calls, and whether debounce might be a better alternative in some cases. By the end, you’ll have a solid understanding of when and how to use these hooks effectively in your React applications.useCallback
A common mistake developers make is defining the debounced function directly inside the React component. Let's look at an example:
import React, { useState } from 'react'; import { debounce } from 'lodash'; const SearchInput = () => { const [query, setQuery] = useState(''); const debouncedSearch = debounce((value) => { console.log('Searching for:', value); }, 500); const handleChange = (e) => { setQuery(e.target.value); debouncedSearch(e.target.value); }; return <input type="text" value={query} onChange={handleChange} />; }; export default SearchInput;
At first glance, this code might seem fine, but there's a hidden issue. Every time the component re-renders, a new instance of debouncedSearch is created. As a result:
To prevent from being recreated on each render, we can memoize it using debouncedSearch.useMemo
import React, { useState, useMemo } from 'react'; import { debounce } from 'lodash'; const SearchInput = () => { const [query, setQuery] = useState(''); const debouncedSearch = useMemo(() => debounce((value) => { console.log('Searching for:', value); }, 500), []); const handleChange = (e) => { setQuery(e.target.value); debouncedSearch(e.target.value); }; return <input type="text" value={query} onChange={handleChange} />; }; export default SearchInput;
useMemo ensures that debouncedSearch is created only once when the component mounts.
While works, an even better approach in this case is using useMemo, since we are memoizing a function:useCallback
import React, { useState, useCallback } from 'react'; import { debounce } from 'lodash'; const SearchInput = () => { const [query, setQuery] = useState(''); const debouncedSearch = useCallback(debounce((value) => { console.log('Searching for:', value); }, 500), []); const handleChange = (e) => { setQuery(e.target.value); debouncedSearch(e.target.value); }; return <input type="text" value={query} onChange={handleChange} />; }; export default SearchInput;
| Hook | Purpose |
|---|---|
| Memoizes values (e.g., computed objects, arrays, or results of expensive calculations). |
| Memoizes functions to prevent re-creation across renders. |
Since is a function, debouncedSearch is a more appropriate choice.useCallback
By default, defining a function inside a React component leads to function recreation on every render, breaking the intended behavior. Memoizing with debounce or useMemo ensures stability, leading to better performance and correct debouncing.useCallback
Yes! It's absolutely possible to implement a debounce function from scratch. However, we often use Lodash's because it is optimized, battle-tested, and handles edge cases more effectively.debounce
Posted by