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

window对象何时为undefined?useLocalStorage钩子校验原因解析

关于自定义useLocalStorage钩子的两个疑问解答

1. 为什么要校验typeof window === "undefined"?

localStorage是浏览器环境下window对象的专属属性,如果直接访问window.localStorage,当window不存在时会抛出引用错误(ReferenceError)。通过typeof window的校验,可以提前判断运行环境:如果当前没有window,就直接返回初始值initialValue,避免代码崩溃,让这个钩子能在非浏览器环境下也正常运行。

2. window对象在什么场景下会是undefined?

常见的场景包括:

  • 服务器端渲染(SSR):比如使用Next.js、Nuxt.js等框架时,组件代码会先在服务器端执行一次,服务器环境基于Node.js,没有浏览器的window对象。
  • 静态站点生成(SSG)/预渲染:例如Next.js的getStaticProps、Gatsby的构建阶段,代码在Node环境下运行,同样不存在window。
  • 非浏览器JavaScript环境:比如直接运行的Node.js脚本、Electron的主进程(主进程基于Node.js,只有渲染进程才有window)。
  • 测试环境:部分测试框架(如Jest默认配置)会模拟非浏览器环境,此时window可能未被定义。

示例钩子代码

function useLocalStorage(key, initialValue) {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once
  const [storedValue, setStoredValue] = useState(() => {
    if (typeof window === "undefined") {
      return initialValue;
    }
    try {
      // Get from local storage by key
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error also return initialValue
      console.log(error);
      return initialValue;
    }
  });
  // Return a wrapped version of useState's setter function that ...
  // ... persists the new value to localStorage.
  const setValue = (value) => {
    try {
      // Allow value to be a function so we have same API as useState
      const valueToStore =
        value instanceof Function ? value(storedValue) : value;
      // Save state
      setStoredValue(valueToStore);
      // Save to local storage
      if (typeof window !== "undefined") {
        window.localStorage.setItem(key, JSON.stringify(valueToStore));
      }
    } catch (error) {
      // A more advanced implementation would handle the error case
      console.log(error);
    }
  };
  return [storedValue, setValue];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:36:27