DEV Community

Manish KC
Manish KC

Posted on • Edited on

Debounce Input in React

Debouncing an input is a technique used to improve web application performance and user experience. When a user types into an input field, the application may perform several operations, such as filtering a list, fetching data from an API, or performing other processes based on the user's input. These operations can be computationally expensive and slow down the application or even cause it to crash if performed too frequently.

Debouncing an input in React involves setting a delay between when a user types into an input and when the input's value is updated.

To create a debounce input in react you can use the following steps.

Solution 1

First we use the useState hook provided by React to store the input variable in a state.

const [inputValue, setInputValue] = React.useState("")
Enter fullscreen mode Exit fullscreen mode

Then we create a function called handleInputChange which will handle the input changes and then update the input value with setInputValue

const handleInputChange = (event) => {
   setInputValue(event.target.value);
}
Enter fullscreen mode Exit fullscreen mode

Moving forward we again use the useState hook provided by React to store the debounced input value

const [debouncedInputValue, setDebouncedInputValue] = React.useState("")
Enter fullscreen mode Exit fullscreen mode

Now we use the useEffect hook and perform a delay before we update the debouncedInputValue.

React.useEffect(() => {
  const delayInputTimeoutId = setTimeout(() => {
    setDebouncedInputValue(inputValue);
  }, 500);
  return () => clearTimeout(delayInputTimeoutId);
}, [inputValue, 500]);
Enter fullscreen mode Exit fullscreen mode

500 milliseconds is used as the delay time to update the deboucedInputValue. We can add the time according to our requirements.

The useEffect will run every time the inputValue changes, after which the delay of 500 milliseconds will happen, and then the deboucneInputValue get updated with the inputValue

Now we can use the debounceInputValue while calling the API or wherever needed. Here the full solution

import React from "react";

const DebounceInput = () => {
  const [inputValue, setInputValue] = React.useState("");
  const [debouncedInputValue, setDebouncedInputValue] = React.useState("");

  const handleInputChange = (event) => {
    setInputValue(event.target.value);
  };

  React.useEffect(() => {
    const timeoutId = setTimeout(() => {
      setDebouncedValue(inputValue);
    }, 500);
    return () => clearTimeout(timeoutId);
  }, [inputValue, 500]);

  return <input type="text" value={inputValue} onChange={handleInputChange} />;
};

Enter fullscreen mode Exit fullscreen mode

Solution 2

For this solution we will be using the debounce function from use-debounce

Firstly we will need to install lodash in our application by running the following command

npm install use-debounce
Enter fullscreen mode Exit fullscreen mode

Then we import the debounce function from use-debounce in out React component

import { useDebounce } from "use-debounce";
Enter fullscreen mode Exit fullscreen mode

After the import is done state is declared for storing the input value

const [inputValue, setInputValue] = React.useState("");
Enter fullscreen mode Exit fullscreen mode

Then we create a function called handleInputChange which will handle the input changes and then update the input value with setInputValue

const handleInputChange = (event) => {
   setInputValue(event.target.value);
}
Enter fullscreen mode Exit fullscreen mode

Then we will use the useDebounce hook to debounce the input value. The first argument of useDebounce takes the input value, and the second argument takes the time for the delay. Then the hook will return debounced value which is debouncedValue.

const [debouncedValue] = useDebounce(inputValue, 500);
Enter fullscreen mode Exit fullscreen mode

Now we can use the debouncedValue wherever necessary.Here is the full solution

import React from "react";
import { useDebounce } from "use-debounce";
const DebounceInput = () => {
  const [inputValue, setInputValue] = React.useState("");
  const [debouncedValue] = useDebounce(inputValue, 500);

  const handleInputChange = (event) => {
    const value = event.target.value;
    setInputValue(value);
  };

  return <input type="text" value={inputValue} onChange={handleInputChange} />;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
asimdahall profile image
Asim Dahal

Really useful and informative, thank you!

Collapse
 
la_tiuscia profile image
la_tiuscia • Edited

no it's wrong

Collapse
 
la_tiuscia profile image
la_tiuscia

how can a constant (500) be a dependency of useEffect? it will never trigger useEffect more than one, which is the first load of the component

Collapse
 
guilherme_b_v_bahia profile image
Guilherme Bahia

Thanks! It was very useful.

Collapse
 
davidko5 profile image
Davyd Kondratenko

Why is there '500' as a dependency in useEffect in first solution?

Collapse
 
corscheid profile image
Corey Scheideman

idk, I'm pretty sure you're right and that number 500 shouldn't be there. It's literally impossible for the literal number 500 to ever change to become any other value. ๐Ÿ˜… I suspect that there was maybe an inadvertently partial refactor here.

Collapse
 
jsbosnic profile image
jsbosnic

Thanks! Just what I needed to learn.
(I think there is a typo at the start of Solution 2, you mention "use-debounce" but then install "lodash").