I am using a custom hook useInstantSearch in my component.
When I wrap it in useCallback to I get the following error:
React Hook useCallback received a function whose dependencies are unknown. Pass an inline function instead.
This is the code:
const [searchTerm, setSearchTerm] = useState<string>(searchQuery);
const handleDebouncedSearch = useCallback(
useInstantSearch(searchTerm, (search, cancelTrigger, searchStillValid) => {
console.log('instant search', search);
}),
[]
);
useEffect((): void => {
handleDebouncedSearch(searchTerm);
}, [searchTerm, handleDebouncedSearch]);
So effectively to send the updated search term to a child component for display only then the parent handles the debouncing of the search when that term changes.
search, cancelTrigger, searchStillValid
Are not part of the parent component, they are part of useInstantSearch.
Is this a warning I can ignore?
import { useEffect, useRef } from 'react';
import { CancelTrigger } from '../../../ars/api/api.cancel';
const DELAY_SEARCH_MS = 300;
interface InstantSearchOnChange {
(search: string, cancelTrigger: CancelTrigger, resultStillValid: { (): boolean }): void;
}
/**
* Helper to delay request until user stop typing (300ms), support deprecated requests (cancel and helper to not update the state), or unmounted component.
*/
export default function useInstantSearch(initialSearch: string, onChange: InstantSearchOnChange): { (value: string): void } {
const search = useRef<string>(initialSearch);
const requests = useRef<CancelTrigger[]>([]);
const mounted = useRef<boolean>(true);
useEffect(() => {
return (): void => {
mounted.current = false;
};
}, []);
return value => {
search.current = value;
setTimeout(() => {
if (search.current === value) {
requests.current = requests.current.filter(r => !r.cancel());
const trigger = new CancelTrigger();
requests.current.push(trigger);
onChange(value, trigger, () => search.current === value && mounted.current);
}
}, DELAY_SEARCH_MS);
};
}