state 状态相关

useGetState

给 React.useState 增加了一个 getter 方法,以获取当前最新值。

js 复制代码
import { useState, useCallback } from 'react';

export type SetState<S> = S | ((prevState: S) => S);

function useGetState<S>(initialState: S | (() => S)) {
  const [state, setState] = useState(initialState);
  
  // 使用 ref 保存最新的 state 值
  const stateRef = useRef(state);
  stateRef.current = state;
  
  // 获取当前状态的方法
  const getState = useCallback(() => stateRef.current, []);
  
  // 包装 setState,同时更新 ref
  const setSetState = useCallback((setStateAction: SetState<S>) => {
    setState(prevState => {
      const nextState = setStateAction instanceof Function 
        ? setStateAction(prevState) 
        : setStateAction;
      stateRef.current = nextState;
      return nextState;
    });
  }, []);

  return [state, setSetState, getState] as const;
}

useResetState

提供重置 state 方法的 Hooks,用法与 React.useState 基本一致。

js 复制代码
import { useState, useRef, useCallback } from 'react';

type Dispatch<T> = (value: T | ((prevState: T) => T)) => void;

function useResetState<S>(initialState: S | (() => S)): [S, Dispatch<S>, () => void] {
  const [state, setState] = useState(initialState);
  const initialRef = useRef(initialState);
  
  const reset = useCallback(() => {
    setState(initialRef.current);
  }, []);
  
  return [state, setState, reset];
}
相关推荐
Csvn31 分钟前
框架性能优化
前端
回眸&啤酒鸭2 小时前
【回眸】OpenSwarm 多智能体协作系统实战指南
大数据·前端·人工智能
用户69371750013842 小时前
2026,程序员的时代拐点到了
android·前端·后端
大龄秃头程序员2 小时前
一次 iBeacon + BLE 无感解锁方案的实现记录
前端
小兔子2 小时前
Python 的 GIL 与 free-threading:3.13 之后「去 GIL」走到哪一步了
前端
IT_陈寒3 小时前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
guslegend4 小时前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
海码事务所4 小时前
Google Play 新个人开发者账号上架指南:12 人连续 14 天封闭测试怎么做?
前端
田威AI4 小时前
图片内文字翻译的规格:输入输出、保真、自动化、时间与费用
前端·计算机视觉
不可能片场4 小时前
命令行中文变问号 我用环境变量救了场
前端·electron