I am working on a React project where I need to debounce an API call when the user types in a search input. I want to ensure that the API call is only made after the user stops typing for a certain period of time.
Here is my current code:
<code>
import React, { useState, useEffect } from 'react';
function SearchComponent() {
const [query, setQuery] = useState('');
useEffect(() => {
const handler = setTimeout(() => {
// Make API call here
console.log('API call with query: ', query);
}, 300);
return () => {
clearTimeout(handler);
};
}, [query]);
return (
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
);
}
export default SearchComponen
t;
While this works, I'm not sure if this is the best approach. Is there a more efficient or idiomatic way to debounce a function in React using hooks? Any suggestions or improvements would be greatly
</code>
<code>
import React, { useState, useEffect } from 'react';
function SearchComponent() {
const [query, setQuery] = useState('');
useEffect(() => {
const handler = setTimeout(() => {
// Make API call here
console.log('API call with query: ', query);
}, 300);
return () => {
clearTimeout(handler);
};
}, [query]);
return (
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
);
}
export default SearchComponen
t;
While this works, I'm not sure if this is the best approach. Is there a more efficient or idiomatic way to debounce a function in React using hooks? Any suggestions or improvements would be greatly
</code>
import React, { useState, useEffect } from 'react';
function SearchComponent() {
const [query, setQuery] = useState('');
useEffect(() => {
const handler = setTimeout(() => {
// Make API call here
console.log('API call with query: ', query);
}, 300);
return () => {
clearTimeout(handler);
};
}, [query]);
return (
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
);
}
export default SearchComponen
t;
While this works, I'm not sure if this is the best approach. Is there a more efficient or idiomatic way to debounce a function in React using hooks? Any suggestions or improvements would be greatly
New contributor
THASVINI P M IT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.