Skip to content

Instantly share code, notes, and snippets.

@stekhn
Created February 15, 2024 16:42
Show Gist options
  • Save stekhn/cb976713f22046fbbe27c445de28e4d8 to your computer and use it in GitHub Desktop.
Save stekhn/cb976713f22046fbbe27c445de28e4d8 to your computer and use it in GitHub Desktop.
Debounced input component for React onChange events using useCallback and Lodash debounce
import React, { useCallback } from "react";
import { debounce } from "lodash";
export const Input = () => {
const mySlowFunction = (value) => console.log(value);
const debouncedEventHandler = useCallback(
debounce((value) => mySlowFunction(value), 100),
[]
);
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
debouncedEventHandler(event.target.value);
event.preventDefault();
return false;
};
return <input type="number" onChange={handleChange} />;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment