perf(navbar): optimize scroll handler to reduce state updates
- Introduces a local tracking variable in `Navbar` scroll effect to prevent redundant `setState` calls during scroll. - Ensures the state is correctly initialized on mount if the page is already scrolled. - Uses `requestAnimationFrame` for efficient scroll handling. This reduces the number of React reconciliation cycles during scrolling, improving main thread performance. Co-authored-by: ragusa-it <196988693+ragusa-it@users.noreply.github.com>
This commit is contained in:
@@ -25,10 +25,22 @@ export function Navbar() {
|
||||
|
||||
useEffect(() => {
|
||||
let ticking = false;
|
||||
// Optimization: Track last state to avoid redundant setState calls
|
||||
let prevIsScrolled = window.scrollY > 20;
|
||||
|
||||
// Set initial state correctly if page is loaded scrolled down
|
||||
if (prevIsScrolled) {
|
||||
setIsScrolled(true);
|
||||
}
|
||||
|
||||
const handleScroll = () => {
|
||||
if (!ticking) {
|
||||
window.requestAnimationFrame(() => {
|
||||
setIsScrolled(window.scrollY > 20);
|
||||
const currentIsScrolled = window.scrollY > 20;
|
||||
if (currentIsScrolled !== prevIsScrolled) {
|
||||
setIsScrolled(currentIsScrolled);
|
||||
prevIsScrolled = currentIsScrolled;
|
||||
}
|
||||
ticking = false;
|
||||
});
|
||||
ticking = true;
|
||||
|
||||
Reference in New Issue
Block a user