ant-design/components/_util/hooks/useSyncState.ts

19 lines
469 B
TypeScript
Raw Normal View History

import * as React from 'react';
import useForceUpdate from './useForceUpdate';
2022-11-09 17:36:49 +08:00
type UseSyncStateProps<T> = readonly [() => T, (newValue: T) => void];
export default function useSyncState<T>(initialValue: T): UseSyncStateProps<T> {
const ref = React.useRef<T>(initialValue);
const forceUpdate = useForceUpdate();
return [
() => ref.current,
(newValue: T) => {
ref.current = newValue;
// re-render
forceUpdate();
},
2022-11-09 17:36:49 +08:00
] as const;
}