I have a Header component like this
const [small, setSmall] = useState(false)
console.log(window.location.pathname)
console.log(window.location.pathname === '/')
useEffect(() => {
if (typeof window !== "undefined") {
if(window.location.pathname === '/'){
window.addEventListener("scroll", () =>
setSmall(window.scrollY > 640),
);
}
}
}, []);
html:
<nav className={`padding-280px ${ small ? "colorful" : "transparent"}`}
the problem is that when am on different Route, console says false, but Header component changes anyway. any tips?
The useEffect
hook runs only once when the component mounts. This means the window.location.pathname
value from when the component mounted is closed over in callback scope. The logic doesn't invalidate the small
state when not on the home "/"
page.
I suggest using the useMatch
hook to test if on the home "/"
pathname and conditionally apply either the "colorful"
or "transparent"
class when the current location is "/"
and the scroll position is greater than 640px. Don't forget to return a cleanup function to remove the scroll event listener when the component unmounts.
Example:
const homeMatch = useMatch("/");
const [small, setSmall] = useState(false);
useEffect(() => {
const scrollHandler = () => {
setSmall(window.scrollY < 640);
};
if (typeof window !== "undefined") {
window.addEventListener("scroll", scrollHandler, { passive: true });
}
return () => {
window.removeEventListener("scroll", scrollHandler, { passive: true });
};
}, []);
...
<nav
className={[
"padding-280px",
homeMatch && small ? "transparent": "colorful"
].join(" ")}
>
...
</nav>