use-scroll-top.tsx
import { useEffect, useState } from 'react';
export const useScrollTop = (threshold = 10) => {
const [scrolled, setScrolled] = useState(false);
useEffect(() => {
const handleScroll = () => {
if (window.scrollY > threshold) {
setScrolled(true);
} else {
setScrolled(false);
}
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, [threshold]);
return scrolled;
};
navbar.tsx
'use client';
import { useScrollTop } from '@/hooks/use-scroll-top';
import { cn } from '@/lib/utils';
export default function Navbar() {
const scrolled = useScrollTop();
return (
<div className={cn('z-50 bg-background fixed top-0 flex' + ' items-center p-6', scrolled && 'border-b shadow-sm')}>
Navbar!
</div>
);
}