avatar

sunday

Sunday's Blog

  • 首页
主页 解决nextjs15使用useLocalStorage报错的问题
文章

解决nextjs15使用useLocalStorage报错的问题

发表于 2025-03-27 更新于 2025-03- 27
作者 sunday 已删除用户
3~4 分钟 阅读

已经在组件中使用"use client"声明了,还是报错,错误如下:

Unhandled Runtime Error
Error: useLocalStorage is a client-only hook

1.解决方案1-使用 dynamic 导入

import dynamic from 'next/dynamic'
const useLocalStorageComponentNoSSR = dynamic(() => import('./useLocalStorage-component'), {
    ssr: false
})

export default useLocalStorageComponentNoSSR

2.再封装一层,判断是否在客户端环境

写一个ClientOnly组件

"use client";

import React from 'react';
import { useIsClient } from "@uidotdev/usehooks"

type ClientOnlyProps = {
    children: React.ReactNode;
};

export const ClientOnly: React.FC<ClientOnlyProps> = ({ children }) => {
    const isClient = useIsClient();

    // Render children if on client side, otherwise return null
    return isClient ? <>{children}</> : null;
};

然后在page中使用


import { ClientOnly } from "@/components/ClientOnly";
import { UseLocalStorageComponent } from "@/components/useLocalStorage-component";
export default function Page(){
    return (
      <ClientOnly>
         <UseLocalStorageComponent/>       
      </ClientOnly>)
}

疑难杂症, nextjs
疑难杂症 nextjs
许可协议:  CC BY 4.0
分享

相关文章

8月 11, 2025

导致DNS泄露的一些问题

1.首先检测你的设备是否有DNS泄露问题 开启代理的情况下,去这个网站https://ipleak.net/ 看一下是否有显示国内的IP,有的话就是DNS泄露了

7月 25, 2025

解决vscode上python代码无法解析导入

1.已经生成了虚拟环境了,如以下结构 ⏺ your-project/ ├── .gitignore ├── api/ │ └── index.py ├── requirements.txt └── .venv/ └── (虚拟环境文件) 2.vscode上显示如下

3月 27, 2025

解决nextjs15使用useLocalStorage报错的问题

已经在组件中使用"use client"声明了,还是报错,错误如下: Unhandled Runtime Error Error: useLocalStorage is a client-only hook 1.解决方案1-使用 dynamic 导入 import dynamic from 'nex

下一篇

mac上使用nodejs appium控制chrome浏览器

上一篇

nextjs + clerk + supabase + realtime 实时监听数据库更改

最近更新

  • ios18 swiftUI 开发的一些问题
  • Cursor IDE中开发IOS应用——支持热更新
  • nginx + acme 不占用80端口申请证书
  • 免费CDN 阿里云ESA 加速国内网站
  • nextjs15使用ai sdk的一些问题

热门标签

nginx acme 强制跳转HTTPS nodejs 代理 mac 神器 vue3 工具 docker

目录

©2025 sunday. 保留部分权利。

使用 Halo 主题 Chirpy