Create a JavaScript Debounce hook that works with React state.
The hook
This is as simple as it gets, create the following file in your codebase.
Use case 1
A simple use case when we want to listen to changes in a state.
const [username, setUsername] = useState("");
const debouncedUsername = useDebounce(username, 800);
useEffect(() => {
// do the thing...
}, [debouncedUsername]);
Use case 2
This also works with complex form structures, get callbacks when anything or specific attributes change in the state.
const [formValues, setFormValues] = useState({
email: "",
address: { city: "" }
});
// Updates when anything in the form changes
const debouncedFormValues = useDebounce(formValues, 800);
// Updates when something specific in the form changes
const debouncedFormValues = useDebounce(formValues.address, 800);
useEffect(() => {
// do the thing...
}, [debouncedFormValues]);
Finally,
In this post, we explored how we could use JavaScript debounce in React as a hook and use those for keep the code DRY.