How to use Debounce in Search in React js?
In today's lesson, we are going to see how to use debounce in search in React js.
Debounce is like waiting until a user stops typing to fetch search results.
Install the package
First of all, we need to install the package useDebounce.
npm i use-debounce
Implement debounce in search
Next, let's assume that we have a search component that fetches tasks from API when the user starts typing, and we want to delay getting search results for a few milliseconds.
So here we use useDebounce like the code below:
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { useDebounce } from 'use-debounce';
export default function Tasks() {
const [tasks, setTasks] = useState([]);
const [searchTerm , setSearchTerm] = useState('');
const debouncedSearchTerm = useDebounce(searchTerm, 300);
useEffect(() => {
fetchTasks();
}, [debouncedSearchTerm[0]])
const fetchTasks = async () => {
try {
if(debouncedSearchTerm[0] !== ''){
const response = await axios.get(`api/search/${searchTerm}/tasks`);
setTasks(response.data);
}
} catch (error) {
console.log(error);
}
}
return (
<div className="row my-5">
<div className="col-md-12 card">
<div className="row my-3">
<div className="col-md-4">
<div className="form-group">
<input type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search..."
className="form-control rounded-0 border border-dark" />
</div>
</div>
</div>
<div className="card-body">
<table className="table">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
<th>Category</th>
<th>Created</th>
</tr>
</thead>
<tbody>
{
tasks?.map(task => (
<tr key={task.id}>
<td>{task.id}</td>
<td>{task.title}</td>
<td>{task.body}</td>
<td>{task.category.name}</td>
<td>{task.created_at}</td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
</div>
)
}