useIsMountedRef
Hook | Source Code
useIsMountedRef(): RefObject
Hooks into whether component is currently mounted. Useful for controlling when you call state setters during async operations.
Returns
Section titled “Returns”A ref where the current value indicates whether the component is currently mounted.
Example
Section titled “Example” const Component = () => { const [myState, setMyState] = useState('');
const isMountedRef = useIsMountedRef();
useEffect(() => { // Initial load from DB. const loadFromDb = async () => { const data = await MyApiService.getInitialData();
if (isMountedRef.current) { // Avoid setting state in the event the component was unmounted while the call to load was out. setMyState(data); } };
loadFromDb(); }, []); }