Skip to content Skip to sidebar Skip to footer

How To Count How Many Instances Of A React Component Are Mounted?

I've got an Ad component that is dynamically loaded into different pages across an eCommerce application. I'd like to be able to know how many of these components exist in a react

Solution 1:

To count the number of mounted intances of a given component, you can add the following to your component (Ad.js in your case).

importReact, { useEffect } from'react'let instancesCount = 0constAd = (props) => {
  useEffect(() => {
    instancesCount += 1console.log({instancesCount})
    return() => {
      instancesCount -= 1console.log({instancesCount})
    }
  }, [])

  return (
    // Whatever your component does
  )

This will increment instancesCount each time a instance of Ad is mounted to the DOM, and decrement it each time an instance is unmounted, effectively giving you the exact number of mounted instances at any given time. It will also log that number every time an instance is mounted or unmounted.

Requirement: React v > 16.8.0

If you have a lower version of React, or if your Ad component is a class component, use this:

let instancesCount = 0classAdextendsReact.Component {
  componentDidMount = () => {
    instancesCount += 1console.log({instancesCount})
  }
  componentWillUnmount = () => { 
    instancesCount -= 1console.log({instancesCount})
  }

  // Whatever your component does
}

Solution 2:

One simple way to do this is just use the DOM to locate a common class on the component. You don't have to use the React API. So, if the component you are looking for has:

<divclass="unique-component">
 ... rest of component
</div>

Just use:

document.querySelectorAll(".unique-component").length

Post a Comment for "How To Count How Many Instances Of A React Component Are Mounted?"