How to execute a function only after the user stops typing?

przemwo

Przemek Wolnik

Posted on June 18, 2020

How to execute a function only after the user stops typing?

I was implementing simple search functionality. I've added input field with onChange handler. But I wanted to perform actual search method some time after the user stops typing.

Looks like a perfect place to use debounce here, right?

I thought that I would just put debounced search function inside useEffect hook. I also had to make sure that debounced search function will stay the same between renders.

After playing for a while with useCallback hook (replaced later by useRef hook which is more appropriate for this job) I had a working solution.

But...

But on second though it turned out the simplest solution is to use good old friend setTimeout combined with clearTimeout.

So here it is:

import React, { useState, useEffect } from 'react';

export const App = () => {
  const [value, setValue] = useState("");

  const handleOnChange = (event) => {
    setValue(event.target.value);
  };

  useEffect(() => {
    const timeoutId = setTimeout(() => console.log(`I can see you're not typing. I can use "${value}" now!`), 1000);
    return () => clearTimeout(timeoutId);
  }, [value]);

  return(
    <>
      <h1>{value}</h1>
      <input onChange={handleOnChange} value={value} />
    </>
  );
};

PS I found a similar (the same?) solution with the journey explained in more details here: https://joaoforja.com/blog/5-steps-to-perform-a-search-when-user-stops-typing-using-react-+-hooks-in-a-controlled-component/ Enjoy!

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
przemwo
Przemek Wolnik

Posted on June 18, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About