DEV Community

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

Collapse
 
wbialekmerixstudio profile image
WBialekMerixStudio

In this solution useEffect will trigger after the first render, so we will see text in the console without any typing. If we want to fetch some data "onChange" then we will have an extra redundant request.
Maybe a better solution will be to move setTimeout to handleOnChange function?

Collapse
 
przemwo profile image
Przemek Wolnik

Thank you for the comment! I a gree with the "trigger after the first render" issue.
However if we move setTimeout to handleOnChange we will have to take care of handling clear timeout manually (useEffect do it for us with the return callback fn).

The other thing is that logging to the console / fetching some data etc. are side effects to value changes - useEffect seems like a perfect choice here.

I would rather add some extra logic inside useEffect (e.g. using useRef) to make sure that our effect runs only after the second and every subsequent render. What do you think?