mirror of
https://github.com/Kong/insomnia
synced 2024-11-08 14:49:53 +00:00
20 lines
547 B
TypeScript
20 lines
547 B
TypeScript
import { useCallback, useState } from 'react';
|
|
import { useMountedState } from 'react-use';
|
|
|
|
export const useSafeState = <S>(initialValue: S | (() => S)) => {
|
|
const isMounted = useMountedState();
|
|
|
|
const [state, _setState] = useState(initialValue);
|
|
|
|
const setState = useCallback<typeof _setState>((...args) => {
|
|
if (isMounted()) {
|
|
_setState(...args);
|
|
}
|
|
}, [isMounted]);
|
|
|
|
// This needs to happen to force a tuple return type
|
|
const returnValue: [typeof state, typeof setState] = [state, setState];
|
|
|
|
return returnValue;
|
|
};
|