background
This is the first in a series on hooks by handwriting. Difficulty: ⭐️.
The existing input box input, when the user input in the input box will trigger the onChange event, in the onChange event will trigger the back-end interface request.
Now I have received feedback from the test, which requires that the input box be shaken to prevent invalid requests from being sent, resulting in poor user experience.
Now code:
const Test = () = > {
const [inputValue, setInputValue] = useState(' ');
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) = > {
setInputValue(e.target.value);
};
useEffect(() = > {
fetchApi(url, { params: { keyword: inputValue } });
}, [inputValue]);
return <input value={inputValue} onChange={handleChange} />;
};
Copy the code
demand
We need to implement a custom hook: useDebounce, which is used as follows: Pass inputValue and time for buffering and return the value after buffering.
const Test = () = > {
const [inputValue, setInputValue] = useState(' ');
constDebouncedValue = useDebounce (inputValue,1000);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) = > {
setInputValue(e.target.value);
};
useEffect(() = > {
fetchApi(url, { params: { keyword: inputValue } });
}, [debouncedValue]); // Use debouncedValue to create a shake - proof effect
return <input value={inputValue} onChange={handleChange} />;
};
Copy the code
coded
Step 1: Define the input/output structure.
function useDebounce<T> (value: T, delay: number) :T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
return debouncedValue;
}
Copy the code
Step 2: Process delay. The key here is to return the value after the delay period, if the value has not changed.
If a new value comes in, the previous timer is cleared, the new timer is executed, and debouncedValue is replaced when the time is up.
function useDebounce<T> (value: T, delay = 1000) :T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() = > {
const handle = setTimeout(() = > {
setDebouncedValue(value);
}, delay);
return () = > clearTimeout(handle);
}, [value, delay]);
return debouncedValue;
}
Copy the code
conclusion
All the code covered in this article is in a github Demo. Give it a thumbs up ❤️❤️❤️.
You are welcome to leave a comment in the comments section to give better practice!