UNPKG

@gdjiami/hooks

Version:

react hooks for mygzb.com

37 lines (36 loc) 1.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var react_1 = require("react"); /** * 扩展useState,新增了getValue作为第三个参数,可以用于在被缓存的callback中获取到最新的值 * * 在闭包环境,有时候为了性能问题,会使用useCallback缓存回调函数,如果在这个回调函数中依赖外部的 * 状态,就会导致问题,它会缓存会回调创建时的环境。也就是依赖的外部变量是旧的 */ function useRefState(initialState) { var ins = react_1.useRef(); var _a = tslib_1.__read(react_1.useState(function () { // 初始化 var value = typeof initialState === 'function' ? initialState() : initialState; ins.current = value; return value; }), 2), state = _a[0], setState = _a[1]; var setValue = react_1.useCallback(function (value) { if (typeof value === 'function') { setState(function (prevState) { var finalValue = value(prevState); ins.current = finalValue; return finalValue; }); } else { ins.current = value; setState(value); } }, []); return [state, setValue, ins]; } exports.default = useRefState;