How to Check if a React Component is Mounted

In my years of building complex React dashboards for US-based fintech startups, I’ve often run into the infamous “memory leak” warning.

It usually happens when an asynchronous task, like a fetch request, finishes after the user has already navigated away from the page.

If you try to update the state on a component that is no longer there, React isn’t going to be happy about it.

In this tutorial, I will show you exactly how to check if a component is mounted so you can keep your applications clean and performant.

The Problem with Updating Unmounted Components

When I first started working with React 16.8, I noticed that my data-heavy applications would occasionally trigger console errors during navigation.

These errors occur because the code tries to call setState on a component that has been destroyed (unmounted).

While newer versions of React have actually removed the “can’t perform a React state update on an unmounted component” warning, the underlying issue, memory leaks, remains.

If you have a long-running API call or a timer, you don’t want it trying to interact with a UI element that doesn’t exist anymore.

Use the useRef Hook for Manual Tracking

The most reliable way I’ve found to handle this in Functional Components is by using the useRef hook.

Unlike a state, a ref doesn’t trigger a re-render, making it the perfect “instance variable” to track the lifecycle of your component.

In this example, imagine we are building a stock price tracker for a New York-based brokerage firm.

import React, { useState, useEffect, useRef } from 'react';

const StockPriceTracker = () => {
  const [price, setPrice] = useState(0);
  const [loading, setLoading] = useState(true);
  
  // Create a ref to track the mounted status
  const isMounted = useRef(true);

  useEffect(() => {
    // When the component mounts, isMounted.current is true
    const fetchStockData = async () => {
      try {
        // Simulating an API call to a US Stock Exchange
        const response = await fetch('https://api.example.com/stocks/AAPL');
        const data = await response.json();

        // Only update state if the component is still mounted
        if (isMounted.current) {
          setPrice(data.price);
          setLoading(false);
        }
      } catch (error) {
        if (isMounted.current) {
          console.error("Failed to fetch data:", error);
        }
      }
    };

    fetchStockData();

    // Cleanup function sets the ref to false when unmounting
    return () => {
      isMounted.current = false;
    };
  }, []);

  return (
    <div style={{ padding: '20px', fontFamily: 'Arial' }}>
      <h1>Apple Inc. (AAPL) Live Price</h1>
      {loading ? (
        <p>Fetching latest market data from NASDAQ...</p>
      ) : (
        <p style={{ fontSize: '24px', fontWeight: 'bold' }}>
          Current Price: ${price}
        </p>
      )}
    </div>
  );
};

export default StockPriceTracker;

You can see the output in the screenshot below.

Check if React Component is Mounted

I prefer this method because it is explicit and very easy for other developers on my team to read and maintain.

Create a Custom useIsMounted Hook

If you find yourself needing this logic across multiple parts of your application, like a large e-commerce site, you should abstract it.

I usually create a custom hook called useIsMounted to keep my component logic DRY (Don’t Repeat Yourself).

This allows me to check the status of any component with a single line of code.

import { useRef, useEffect, useCallback } from 'react';

// Custom hook to track mounting status
const useIsMounted = () => {
  const isMounted = useRef(false);

  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);

  // Return a function that returns the current value
  return useCallback(() => isMounted.current, []);
};

// Example usage in a Seattle-based Real Estate Listing app
import React, { useState } from 'react';

const PropertyListing = () => {
  const [property, setProperty] = useState(null);
  const getIsMounted = useIsMounted();

  const loadPropertyData = async () => {
    const response = await fetch('https://api.example.com/listings/seattle-downtown');
    const data = await response.json();

    // Use the custom hook to check status
    if (getIsMounted()) {
      setProperty(data);
    }
  };

  return (
    <div>
      <h2>Seattle Luxury Apartments</h2>
      <button onClick={loadPropertyData}>View Details</button>
      {property && <div>{property.name} - ${property.price}</div>}
    </div>
  );
};

You can see the output in the screenshot below.

How to Check if a React Component is Mounted

Using a function return in the custom hook (via useCallback) is a pattern I’ve found that prevents stale closure issues.

Handle Mounting in Class Components

While I mostly work with Functional Components these days, many legacy enterprise systems in the US still use Class Components.

In a Class Component, we don’t have hooks, so we manually attach a property to the class instance.

Here is how I handled this when maintaining a legacy banking application.

import React, { Component } from 'react';

class UserProfile extends Component {
  // Initialize the property
  _isMounted = false;

  constructor(props) {
    super(props);
    this.state = {
      userData: null,
    };
  }

  componentDidMount() {
    this._isMounted = true;
    
    // Simulating a fetch for a user profile in Chicago
    fetch('https://api.example.com/users/chicago-office/101')
      .then(response => response.json())
      .then(data => {
        if (this._isMounted) {
          this.setState({ userData: data });
        }
      });
  }

  componentWillUnmount() {
    // Set to false right before the component is destroyed
    this._isMounted = false;
  }

  render() {
    return (
      <div>
        <h3>Employee Directory</h3>
        {this.state.userData ? (
          <p>Welcome back, {this.state.userData.name}!</p>
        ) : (
          <p>Loading profile...</p>
        )}
      </div>
    );
  }
}

export default UserProfile;

You can see the output in the screenshot below.

Check if Component is Mounted in React

The underscore prefix (_isMounted) is a common convention I use to indicate that this is a private variable not meant for rendering.

Why Aborting Requests is Often Better

While checking if a component is mounted is useful, I often suggest a more modern approach: AbortController.

Instead of just checking if the component is there, you actually cancel the network request entirely.

This is much better for users on slower mobile networks in rural areas of the US, as it saves bandwidth.

import React, { useState, useEffect } from 'react';

const WeatherReport = () => {
  const [weather, setWeather] = useState('');

  useEffect(() => {
    const controller = new AbortController();
    const signal = controller.signal;

    const fetchWeather = async () => {
      try {
        // Fetching weather for Denver, Colorado
        const response = await fetch('https://api.weather.gov/gridpoints/BOU/62,61/forecast', { signal });
        const data = await response.json();
        setWeather(data.properties.periods[0].detailedForecast);
      } catch (err) {
        if (err.name === 'AbortError') {
          console.log('Fetch aborted: Component unmounted');
        } else {
          console.error('Fetch error:', err);
        }
      }
    };

    fetchWeather();

    // Abort the fetch if the component unmounts
    return () => controller.abort();
  }, []);

  return (
    <div style={{ border: '1px solid #ccc', margin: '10px', padding: '10px' }}>
      <h4>Denver Local Forecast</h4>
      <p>{weather || 'Loading forecast...'}</p>
    </div>
  );
};

I find this to be the cleanest “pro-level” solution because it solves the root cause of the problem.

Summary of Techniques

Over the years, I’ve learned that there isn’t just one way to solve this, but rather the best way for each situation.

If you are just preventing a state update, the useRef method is incredibly quick and effective.

For larger projects, the custom hook keeps your code organized and prevents repetition.

If you are dealing with network calls, always try to use AbortController first before falling back to mounting checks.

I hope this helps you write cleaner, bug-free React code for your next big project.

In this tutorial, I have covered several ways to check if a React component is mounted, from using refs to implementing custom hooks.

You may also like to read other articles on React:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.