The React hook useScroll can incorrectly reflect the initial scrolled state. This happens on first render, when the user's starting y-position is greater than the threshold. The state reports false when it should say true.
Here, you can see we've started with a vertical scroll position beyond the threshold. As such, the Navbar should have a slightly opaque background; however, it's completely transparent.
Solution
One way to fix this is by checking the user's initial y-position on first mount. We do that by invoking the onScroll handler when also registering it as a scroll event listener. That way, we don't rely on a scrolled event to correctly update the state. Note: it will always render as false on the server, but corrects itself immediately when the client first renders the component.
Here, we see our solution implemented and Navbar has the background we'd expect.
Description
The React hook
useScroll
can incorrectly reflect the initialscrolled
state. This happens on first render, when the user's starting y-position is greater than thethreshold
. The state reportsfalse
when it should saytrue
.Here, you can see we've started with a vertical scroll position beyond the threshold. As such, the
Navbar
should have a slightly opaque background; however, it's completely transparent.Solution
One way to fix this is by checking the user's initial y-position on first mount. We do that by invoking the
onScroll
handler when also registering it as a scroll event listener. That way, we don't rely on a scrolled event to correctly update the state. Note: it will always render asfalse
on the server, but corrects itself immediately when the client first renders the component.Here, we see our solution implemented and
Navbar
has the background we'd expect.