I'm trying to set onTop state to true if the user has scrolled to the top and false otherwise. I tried the following.
function Test()
{
const [ onTop, setOnTop ] = useState( true )
const watchScroll = () =>
{
if ( window.scrollY < 100 ) setOnTop( true )
else setOnTop( false )
}
useEffect(() => {
window.addEventListener(`scroll`, watchScroll )
return window.removeEventListener(`scroll`, watchScroll )
}, [ watchScroll ])
return (
<div>{ onTop ? `On Top` : `Not On top` }</div>
)
}
The above example doesn't work but throws no error either.
function Test()
{
const [ onTop, setOnTop ] = useState( true )
const watchScroll = () =>
{
if ( window.scrollY < 100 ) setOnTop( true )
else setOnTop( false )
}
useEffect(() => {
window.addEventListener(`scroll`, () => watchScroll() )
return window.removeEventListener(`scroll`, () => watchScroll() )
}, [ watchScroll ])
return (
<div>{ onTop ? `On Top` : `Not On top` }</div>
)
}
Note that I added an arrow and braces to the second parameter function. The above example works as intended. Can anyone explain why? Thanks very much!