Last active
September 8, 2023 08:16
-
-
Save mustafadalga/1269ebc9ff9d4c3819f89d5644cbf742 to your computer and use it in GitHub Desktop.
Debounced Search Component in React:This React component demonstrates how to implement a debounced search feature using hooks like `useState`, `useEffect`, and `useCallback`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ChangeEvent, useCallback, useEffect, useState } from "react"; | |
import { CiSearch } from "react-icons/ci" | |
import { useSearch } from "@/store/useSearch"; | |
const Search = () => { | |
const [ searchText, setSearchText ] = useState(""); | |
const setSearch = useSearch(state => state.setSearch); | |
const [ debouncedSearchText, setDebouncedSearchText ] = useState(searchText); | |
const handleSearchText = useCallback((event: ChangeEvent<HTMLInputElement>) => { | |
const value = event.target.value; | |
setSearchText(value); | |
}, []) | |
// Debounce logic | |
useEffect(() => { | |
const timerId = setTimeout(() => { | |
setDebouncedSearchText(searchText); | |
}, 300); // 300ms delay | |
// Cleanup | |
return () => { | |
clearTimeout(timerId); | |
}; | |
}, [ searchText ]); | |
// Update the search when debouncedSearchText changes | |
useEffect(() => { | |
setSearch(debouncedSearchText); | |
}, [ debouncedSearchText, setSearch ]); | |
return ( | |
<form className="group"> | |
<label htmlFor="default-search" | |
className="mb-2 text-sm font-medium text-gray-900 sr-only">Search</label> | |
<div className="relative"> | |
<input type="search" id="default-search" | |
value={searchText} | |
onChange={handleSearchText} | |
className="block w-full peer p-4 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:border-primary focus:outline-none" | |
placeholder="Search Variable..." | |
required/> | |
<div | |
className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none peer-focus:text-primary"> | |
<CiSearch className="text-2xl"/> | |
</div> | |
</div> | |
</form> | |
); | |
}; | |
export default Search; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment