steven-tey / precedent

An opinionated collection of components, hooks, and utilities for your Next.js project.
https://precedent.dev
MIT License
4.65k stars 406 forks source link

[Fix] Update React hook `useScroll` #71

Open KentHHarris opened 8 months ago

KentHHarris commented 8 months ago

Description

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.

Screenshot 2023-10-18 at 3 36 51 PM

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.

Screenshot 2023-10-18 at 3 37 09 PM
vercel[bot] commented 8 months ago

@KentHHarris is attempting to deploy a commit to the Elegance Team on Vercel.

A member of the Team first needs to authorize it.