0

My idea was when user types the email in the input box when stops for 500 milliseconds that time only useEffects side effect will run other wise user continusly types side effects will not run that will clear with help of cleanUp function. side effects runs frist time when the app starts. After that any dependency changed cleanup function runs therafter side effects runs. so if i create setTimeout function in the side effects with 500 milliseconds and I clear the timeout function in the cleanup function it will clear the side effect. But when user stops typing in the input box in that time also dependency changed clenup function need to clear the side effects. But cleanup function runs properly but not clear the side effects side effects also runs how it possible? why cleanup function not clear the side effects in the user stop typing

useEffect(() => {
  const timeoutHandler = setTimeout(() => {
    setFormIsValid(
      enteredEmail.includes("@") && enteredPassword.trim().length > 6
    );
    console.log("side effect");
  }, 500);

  return () => {
    clearTimeout(timeoutHandler);
    console.log("cleanUp function");
  };
}, [enteredEmail, enteredPassword]);
  • Does this help answer your question? https://stackoverflow.com/q/70269424/8690857 – Drew Reese Jan 10 '23 at 10:11
  • The problem is that the useEffect hook does not track the actual time that has passed, it only tracks whether the dependencies have changed. – Farouk Allani Jan 10 '23 at 10:16
  • You need to create the timeout outside of your effect. Otherwise you create a new timeout everytime the user is typing. – MaatMa Jan 10 '23 at 11:10
  • your problem will be solved using the concept of debouncing. refer link to learn how it work https://www.youtube.com/watch?v=tJhA0DrH5co&ab_channel=AkshaySaini – yograj tandel Jan 10 '23 at 11:53

0 Answers0