I want to run some client only code on a page route, to detect scroll position and set a state variable to true at a certain scroll position, and I have tried to use this code in a useEffect and am still getting an error. I don't want to wrap a whole page route in ClientOnly (that is if I even can) because I don't want to lose the ability to run stuff on the server
#How can I access window in useEffect without importing ClientOnly util from remix-utils
1 messages · Page 1 of 1 (latest)
React.useEffect(() => {
if (typeof window !== undefined && window?.scrollY > 20) {
setShowBottomButton(true);
} else {
setShowBottomButton(false);
}
}, [window?.scrollY]);
effects runs only client-side, so it should be safe to use window there
I get an error with the above code
there's no scenario where window is not defined inside an effect or event handler
try to create a replication in CodeSandbox
if I try to navigate from one route to this route it doesn't break until page refresh happens
ahh I just saw the issue
the dependency array includes window
that will run server-side
but you don't need that
because React don't have a way to listen to changes in the window object
so it does nothing, unless window is a state
Just to add onto Sergio’s answer, if you want a button to appear based on the window scroll position, you should put that logic inside of an event listener that listens for the scroll event. That is you want to call addEventListener inside your useEffect, and remember to also clean up the effect with removeEventListener
Thanks, I actually did figure it out the way you had explained @wicked lark but it was causing a rerender with every scroll position change and I decided to just keep the button static and always rendered at that viewport for now, I may revisit this in the future