ahooks
Version:
react hooks library
16 lines (15 loc) • 525 B
JavaScript
import { useCallback, useState } from 'react';
import useUnmountedRef from '../useUnmountedRef';
function useSafeState(initialState) {
const unmountedRef = useUnmountedRef();
const [state, setState] = useState(initialState);
const setCurrentState = useCallback((currentState) => {
/** if component is unmounted, stop update */
if (unmountedRef.current) {
return;
}
setState(currentState);
}, []);
return [state, setCurrentState];
}
export default useSafeState;