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 :
By default React will re-render the component for any state change, so your console.log is being called during the re-render.