React 中的闭包问题
Published on October 31, 2023Updated on March 23, 2024
Loading content...
React TSXconst useStateWithRef = initialVal => { const [state, setState] = useState(initialVal); const ref = useRef(initialVal); const setStateCopy = newVal => { ref.current = newVal; setState(newVal); }; const getState = () => ref.current; return [state, setStateCopy, getState]; };
https://ahooks.js.org/hooks/use-get-state
TypeScriptfunction useGetState<S>(initialState?: S) { const [state, setState] = useState(initialState); const stateRef = useRef(state); stateRef.current = state; const getState = useCallback(() => stateRef.current, []); return [state, setState, getState]; } export default useGetState;