2023-05-06 15:49:37 +08:00
|
|
|
import * as React from 'react';
|
2023-09-20 11:01:49 +08:00
|
|
|
|
2020-08-18 15:44:31 +08:00
|
|
|
import useForceUpdate from './useForceUpdate';
|
|
|
|
|
2022-11-09 17:36:49 +08:00
|
|
|
type UseSyncStateProps<T> = readonly [() => T, (newValue: T) => void];
|
2020-08-18 15:44:31 +08:00
|
|
|
|
|
|
|
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;
|
2020-08-18 15:44:31 +08:00
|
|
|
}
|