Last active
June 17, 2022 03:55
-
-
Save luigircruz/c787fe4a15bf09fc9163c5ebfe1df3d4 to your computer and use it in GitHub Desktop.
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 { useState, useEffect } from "react"; | |
| export default function useDebounce(value, delay) { | |
| const [debouncedValue, setDebouncedValue] = useState(value); | |
| useEffect(() => { | |
| const handler = setTimeout(() => { | |
| setDebouncedValue(value); | |
| }, delay); | |
| return () => { | |
| clearTimeout(handler); | |
| }; | |
| }, [value, delay]); | |
| return debouncedValue; | |
| } | |
| // Use the hook on your component | |
| // Example... | |
| import { useState, useEffect } from "react"; | |
| import useDebounce from "./utils/useDebounce"; | |
| export default function SampleComponent() { | |
| const [val, setVal] = useState(""); | |
| const [debounceVal, setDebounceVal] = useState(val); | |
| const debouncedInputValue = useDebounce(val, 1000); | |
| useEffect(() => { | |
| if (debouncedInputValue) { | |
| setDebounceVal(debouncedInputValue); | |
| } | |
| }, [debouncedInputValue]); | |
| const handleChange = ({ currentTarget }) => { | |
| setVal(currentTarget.value); | |
| }; | |
| return ( | |
| <div className="App"> | |
| <div> | |
| <input | |
| type="text" | |
| value={val} | |
| placeholder="Debounced input" | |
| onChange={handleChange} | |
| /> | |
| </div> | |
| <div>Debounced value: {debounceVal}</div> | |
| </div> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment