skip to Main Content

Can someone explain me why every time I call setTest(scrollY) I can console.log(scrollY) every time I scroll and I don’t even need to use test. But if I don’t call it then it only logs scrollY once?

const [test, setTest] = useState(0);

useEffect(function () {
  function handleScroll() {
    setTest(scrollY);
}

  handleScroll();
  window.addEventListener("scroll", handleScroll);

  return function () {
    window.removeEventListener("scroll", handleScroll);
  };
}, []);

return (
  {console.log(scrollY)}
)

2

Answers


  1. By default React will re-render the component for any state change, so your console.log is being called during the re-render.

    Login or Signup to reply.
  2. This is because of the Reactive behaviour of ReactJs,
    Whenever you call setTest, it will update the state test, Triggering a rerender of the component.

    Hence console.log is printing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search