What's the use of window.onscroll = null here? It shows no difference even when i comment that last line out.
const [isScrolled, setIsScrolled] = useState(false);
window.onscroll = () => {
setIsScrolled(window.pageYOffset === 0? false : true)
console.log(isScrolled);
return () => (window.onscroll = null);
};
CodePudding user response:
Removes the event handler added to onScroll event. But better to move it inside useEffect hook.
CodePudding user response:
As written, the window.onscroll = null is useless. It will never be executed. However, this code is suspiciously close to code that is useful. The following code is what i would expect to see:
const [isScrolled, setIsScrolled] = useState(false);
useEffect(() => {
window.onscroll = () => {
setIsScrolled(window.pageYOffset === 0? false : true)
};
return () => (window.onscroll = null);
}, []);
In this modified version, return () => (window.onscroll = null) is returning a cleanup function for the effect. When the component unmounts, this function runs and removes the event listener. This is important to do so that you avoid memory leaks.
