You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化控制导航栏可见性的React Hook性能?

优化滚动控制NavBar可见性的React Hook性能方案

你的这个Hook目标是复刻Humboldt Forum的导航栏行为,但原代码存在性能损耗和逻辑漏洞,下面是具体的优化方向和最终代码:

核心优化点

  • 节流滚动事件:scroll事件每秒能触发几十上百次,直接执行回调会造成不必要的性能消耗,用节流限制回调执行频率(比如每100ms一次)
  • 避免闭包陷阱:原代码里handleScroll依赖的currentScrollPos是组件渲染时的旧值,逻辑判断会出错,应该直接在回调里取实时的window.scrollY
  • 用Ref替代不必要的State:像lastScrollTime、prevScrollPos这类不需要触发重渲染的值,用useRef存储比useState更高效,减少组件重渲染次数
  • 修正事件绑定逻辑:原useEffect依赖window.scrollY会导致每次滚动都重复绑定/解绑事件,改成只在组件挂载时绑定一次,卸载时解绑
  • 简化状态更新逻辑:去掉冗余的currentScrollPos状态,直接在回调里获取滚动位置,减少不必要的状态更新

优化后的完整代码

import { useState, useEffect, useRef, useCallback } from 'react';

const useScrollSpeed = (navHeight: number, maxScrollSpeed: number, throttleDelay = 100) => {
  const [visible, setVisible] = useState(true);
  const prevScrollPos = useRef(0);
  const lastScrollTime = useRef(new Date().getTime());
  const throttleTimeout = useRef<NodeJS.Timeout | null>(null);

  // 节流处理的滚动回调
  const handleScroll = useCallback(() => {
    if (throttleTimeout.current) return;

    throttleTimeout.current = setTimeout(() => {
      const currentScrollPos = window.scrollY;
      const timeDiff = new Date().getTime() - lastScrollTime.current;
      const distance = Math.abs(currentScrollPos - prevScrollPos.current);
      const scrollSpeed = timeDiff > 0 ? distance / timeDiff : 0;

      // 页面顶部时强制显示
      if (currentScrollPos < navHeight) {
        setVisible(true);
      } else {
        // 向下滚动隐藏
        if (currentScrollPos > prevScrollPos.current) {
          setVisible(false);
        } else {
          // 向上滚动且速度达标时显示
          if (scrollSpeed > maxScrollSpeed) {
            setVisible(true);
          }
        }
      }

      // 更新ref的值
      prevScrollPos.current = currentScrollPos;
      lastScrollTime.current = new Date().getTime();
      throttleTimeout.current = null;
    }, throttleDelay);
  }, [navHeight, maxScrollSpeed, throttleDelay]);

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
      if (throttleTimeout.current) {
        clearTimeout(throttleTimeout.current);
      }
    };
  }, [handleScroll]);

  return visible;
};

export default useScrollSpeed;

额外说明

  • 节流延迟throttleDelay设为可选参数,默认100ms,你可以根据需求调整(比如更灵敏就设50ms)
  • 加入了timeDiff > 0的判断,避免初始时时间差为0导致的除以0问题
  • 用useCallback缓存handleScroll,确保useEffect不会因为回调变化重复绑定事件

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 16:52:24