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

如何在刷新页面时保留React useState/useContext的数据?

解决React状态刷新/跳转后丢失的问题

React的useState和useContext状态都是内存级的,页面刷新、用location.replace()跳转时,当前页面的React实例会被销毁,内存里的状态自然就没了。要保留数据,核心是把状态同步到浏览器的持久化存储(sessionStorage/localStorage),下面给你两种直接可用的方案:

1. 自定义持久化版useState

自己封装一个钩子,把状态和存储绑定,不用每次手动操作sessionStorage:

import { useState, useEffect } from 'react';

function usePersistentState(key, defaultValue) {
  // 初始化时从sessionStorage读取,没有就用默认值
  const [state, setState] = useState(() => {
    const storedValue = sessionStorage.getItem(key);
    return storedValue ? JSON.parse(storedValue) : defaultValue;
  });

  // 状态更新时同步到sessionStorage
  useEffect(() => {
    sessionStorage.setItem(key, JSON.stringify(state));
  }, [state, key]);

  return [state, setState];
}

使用示例

// 代替普通useState
const [userInfo, setUserInfo] = usePersistentState('userInfo', { name: '', age: 0 });

这样不管刷新页面还是用location.replace()跳转,新页面里调用这个钩子就能直接拿到之前的状态。

2. 给useContext加上持久化

如果是用useContext管理全局状态,只需要在Context的Provider里用上面的usePersistentState代替普通useState就行:

import { createContext, useContext } from 'react';
import usePersistentState from './usePersistentState';

const AppContext = createContext();

export function AppProvider({ children }) {
  // 用持久化钩子管理context的状态
  const [globalState, setGlobalState] = usePersistentState('appGlobalState', { theme: 'light', token: '' });

  return (
    <AppContext.Provider value={{ globalState, setGlobalState }}>
      {children}
    </AppContext.Provider>
  );
}

// 自定义消费钩子
export function useAppContext() {
  return useContext(AppContext);
}

之后任何组件用useAppContext()拿到的状态,都是持久化后的,刷新/跳转不会丢失。

注意事项

  • 存储选择:如果希望关闭浏览器标签后数据消失用sessionStorage,需要长期保存用localStorage,把上面代码里的sessionStorage换成localStorage就行。
  • 复杂数据:存储只能存字符串,所以要用JSON.stringify和JSON.parse处理对象/数组,注意如果状态里有函数、Symbol这类不能序列化的类型,要提前过滤。
  • 唯一key:每个持久化状态的key要保证唯一,避免不同状态互相覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:50:14