Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why using useState hook lets me use a non useState property?

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)}
)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading