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
By default React will re-render the component for any state change, so your console.log is being called during the re-render.
This is because of the Reactive behaviour of ReactJs,
Whenever you call
setTest
, it will update the statetest
, Triggering a rerender of the component.Hence
console.log
is printing.