React Hooks: useMountedRef

Ward Poel

A React Hook for checking if you component is mounted.


The useMountedRef just give you a ref like you're used to.


Let's say we have an API that fetches a person. If we click accidentally on the wrong person, we fetch a person we don't want. But because react renders the Person component, the API request is also fired. Let's say we now go back to our previous screen. The request is still going on, when the request is done we try to set the state, but this component is unmounted so React will throw a warning. You can easily avoid this by checking if the component is still mounted before setting the state.

export default function Person(props) {
	let { id } = props;
	let mountedRef = useMountedRef();
	let [person, setPeron] = useState();

	useEffect(() => {
		async function fetchPerson() {
			let response = await fetch('/api/person/' + id);
			let data = await response.json();
			if (mountedRef.current) {

	}, [id])

	if (person == undefined) return <div>Loading...</div>

	return <h1>{}</h1>

The hook

import { useRef, useEffect } from 'react';

export default function useMountedRef() {
	let mounted = useRef(false);

	useEffect(() => {
		mounted.current = true;

		return () => {
			mounted.current = false;
	}, []);

	return mounted;

Checkout my useMountedState hook for a cleaner solution.

If you have any questions, I'm @WardPoel on Twitter.