Kunal Tyagi
Kunal Tyagi

Reputation: 4197

How to Avoid calling setState Function Again and Again?

I am new to React and I need to update the State of a variable only when the value is different from the previous state.
Suppose I have a state with initial value false

const [open, setOpen] = useState(false);

I need to update the state of the variable on Horizontal Scroll, I have attached a listener on Scroll that will call a function handleClickAway everytime, I scroll

useEffect(() => {
   const scroll = document.querySelector('.myclass');
   scroll.addEventListener("scroll", () => handleClickAway());
   return () => {
       scroll.removeEventListener("scroll", () => handleClickAway());
   };
}, []);

const handleClickAway = () => {
    setOpen(false);
}

Now, here it will update the state everytime by calling setOpen(false) on Scroll, I am not sure how to handle this

I don't want to call the setOpen(false) again if it has already been called and set the value to false on Scroll

Upvotes: 1

Views: 552

Answers (3)

user12711263
user12711263

Reputation:

const handleClickAway = () => {
 if(open) {
   setOpen(false);
 }
}

Upvotes: 0

Rashed Rahat
Rashed Rahat

Reputation: 2495

Here is the solution:

const handleClickAway = () => open && setOpen(false);

Upvotes: 1

Artem Arkhipov
Artem Arkhipov

Reputation: 7465

Just add the if statement and call setOpen only if open is true.

const handleClickAway = () => {
    if (open) {
      setOpen(false);
    }
}

Or a bit shorter way:

const handleClickAway = () => {
  open && setOpen(false);
}

Upvotes: 1

Related Questions