Created
July 27, 2023 13:52
-
-
Save Cornally/6e56d558bba455791d7dd1320e9b7be9 to your computer and use it in GitHub Desktop.
Chat GPT Debounced Hook Example
This file contains 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 React, { useState, useEffect, ChangeEvent } from 'react'; | |
type DebouncedInputHookProps = { | |
delay: number; | |
callback: (value: string) => void; | |
}; | |
type DebouncedInputHookResult = { | |
debouncedValue: string; | |
handleChange: (event: ChangeEvent<HTMLInputElement>) => void; | |
}; | |
const useDebouncedInput = ({ delay, callback }: DebouncedInputHookProps): DebouncedInputHookResult => { | |
const [inputValue, setInputValue] = useState<string>(''); | |
const [debouncedValue, setDebouncedValue] = useState<string>(''); | |
useEffect(() => { | |
const debounceTimer = setTimeout(() => { | |
setDebouncedValue(inputValue); | |
callback(debouncedValue); // Execute the provided callback with the debounced value | |
}, delay); | |
return () => clearTimeout(debounceTimer); | |
}, [inputValue, debouncedValue, delay, callback]); | |
const handleChange = (event: ChangeEvent<HTMLInputElement>) => { | |
setInputValue(event.target.value); | |
}; | |
return { debouncedValue, handleChange }; | |
}; | |
// Usage example | |
const MyComponent = () => { | |
const [searchQuery, setSearchQuery] = useState<string>(''); | |
const handleSearch = (debouncedQuery: string) => { | |
// Perform the search operation here using the debounced value (debouncedQuery) | |
console.log('Searching for:', debouncedQuery); | |
}; | |
// This hook returns the debounced value and a handleChange function | |
const { debouncedValue, handleChange } = useDebouncedInput({ delay: 500, callback: handleSearch }); | |
return ( | |
<div> | |
<input | |
type="text" | |
value={searchQuery} | |
onChange={handleChange} | |
placeholder="Type to search..." | |
/> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment