UNPKG

@react-hookz/web

Version:

React hooks done right, for browser and SSR.

18 lines (17 loc) 535 B
import { useCallback, useState } from 'react'; import { useIsMounted } from '..'; /** * Like `useState` but its state setter is guarded against sets on unmounted component. */ export function useSafeState(initialState) { const [state, setState] = useState(initialState); const isMounted = useIsMounted(true); return [ state, useCallback((value) => { if (isMounted()) setState(value); // eslint-disable-next-line react-hooks/exhaustive-deps }, []), ]; }