Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix] Update React hook useScroll #71

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/hooks/use-scroll.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { useCallback, useEffect, useState } from "react";

/**
* React hook to observe scroll postion.
* @param threshold {number} The y-axis position to observe.
* @returns {boolean} `True` when the user's vertical scroll position is greater than the `threshold`; otherwise, `False`.
*/
export default function useScroll(threshold: number) {
const [scrolled, setScrolled] = useState(false);

Expand All @@ -8,6 +13,8 @@ export default function useScroll(threshold: number) {
}, [threshold]);

useEffect(() => {
window && onScroll(); // Call on first render. This correctly updates the `scrolled` state to `True` if the user's scroll position is greater than the `threshold` during the initial load.

window.addEventListener("scroll", onScroll);
return () => window.removeEventListener("scroll", onScroll);
}, [onScroll]);
Expand Down