How to Get Component Height in React

In my journey of building complex React dashboards for FinTech firms in New York, I’ve often hit a common roadblock.

You need to know the exact height of a component to trigger an animation or position a custom dropdown perfectly.

Getting the height in React isn’t as simple as it was in the days of jQuery, but it is much more powerful once you get the hang of it.

In this tutorial, I will show you exactly how I handle measuring DOM elements using modern React hooks and industry-standard practices.

Why You Might Need a Component’s Height

When I was building a real estate listing app for a client in Chicago, we needed a sticky sidebar that adjusted based on the height of the main property description.

If the description was too long, the sidebar needed to stop at a certain point to avoid overlapping the footer.

You might also need the height for implementing “Read More” toggles, calculating scroll positions, or creating responsive canvas elements.

Method 1: Use the useRef and useEffect Hooks

This is my go-to method for static or initial measurements. It is simple, performant, and works for most use cases.

We use useRef to grab a reference to the DOM element and useEffect to read its properties after the component mounts.

Here is a full example where we calculate the height of a shipping summary card for a US-based e-commerce platform.

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

const ShippingSummary = () => {
  const cardRef = useRef(null);
  const [height, setHeight] = useState(0);

  useEffect(() => {
    // We check if the ref is current to avoid null errors
    if (cardRef.current) {
      const elementHeight = cardRef.current.offsetHeight;
      setHeight(elementHeight);
      console.log("Initial Card Height:", elementHeight);
    }
  }, []); // Empty dependency array ensures this runs once after mount

  const cardStyle = {
    padding: '20px',
    border: '1px solid #ddd',
    borderRadius: '8px',
    backgroundColor: '#f9f9f9',
    width: '350px',
    margin: '20px auto'
  };

  return (
    <div style={{ textAlign: 'center', fontFamily: 'Arial' }}>
      <h2>FedEx Shipping Calculator</h2>
      <div ref={cardRef} style={cardStyle}>
        <h3>Order #77892</h3>
        <p>Origin: Los Angeles, CA</p>
        <p>Destination: Miami, FL</p>
        <p>Package Weight: 12 lbs</p>
        <hr />
        <p>Estimated Delivery: 3 Business Days</p>
      </div>
      <p style={{ fontWeight: 'bold', color: '#007bff' }}>
        The dynamic height of this summary card is: {height}px
      </p>
    </div>
  );
};

export default ShippingSummary;

You can see the output in the screenshot below.

Component Height in React

In this code, offsetHeight includes the vertical padding and borders, which is usually what you want for layout calculations.

Method 2: Handle Dynamic Content with ResizeObserver

Sometimes, the content inside your component changes after the initial render.

I remember working on a live sports betting app where the odds were constantly updating, changing the height of the betting slips.

In these cases, useEffect with an empty array isn’t enough because it only runs once.

The ResizeObserver API is a lifesaver here. It watches the element and fires a callback whenever the dimensions change.

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

const LiveInventoryTracker = () => {
  const containerRef = useRef(null);
  const [componentHeight, setComponentHeight] = useState(0);
  const [items, setItems] = useState(['Standard SKU: 104', 'Express SKU: 205']);

  // useLayoutEffect prevents flickering before the browser paints
  useLayoutEffect(() => {
    if (!containerRef.current) return;

    const resizeObserver = new ResizeObserver((entries) => {
      for (let entry of entries) {
        if (entry.target === containerRef.current) {
          setComponentHeight(entry.contentRect.height);
        }
      }
    });

    resizeObserver.observe(containerRef.current);

    // Cleanup the observer on component unmount
    return () => resizeObserver.disconnect();
  }, []);

  const addItem = () => {
    setItems([...items, `New Batch SKU: ${Math.floor(Math.random() * 1000)}`]);
  };

  const boxStyle = {
    background: '#e3f2fd',
    padding: '15px',
    width: '400px',
    margin: '0 auto',
    borderRadius: '10px'
  };

  return (
    <div style={{ padding: '50px', textAlign: 'center' }}>
      <h1>Inventory Management (Dallas Warehouse)</h1>
      <button 
        onClick={addItem}
        style={{ marginBottom: '20px', padding: '10px 20px', cursor: 'pointer' }}
      >
        Add Inventory Item
      </button>
      
      <div ref={containerRef} style={boxStyle}>
        {items.map((item, index) => (
          <div key={index} style={{ padding: '5px', borderBottom: '1px solid #ccc' }}>
            {item}
          </div>
        ))}
      </div>

      <div style={{ marginTop: '20px', fontSize: '1.2rem' }}>
        Current Container Height: <span style={{ color: 'red' }}>{Math.round(componentHeight)}px</span>
      </div>
    </div>
  );
};

export default LiveInventoryTracker;

You can see the output in the screenshot below.

Get Component Height in React

I used useLayoutEffect here because it triggers synchronously after all DOM mutations.

This is crucial if you want to avoid that “jumpy” feeling where the UI shifts after the user sees it.

Method 3: Use a Custom Hook for Reusability

If you are working on a large-scale project, like a SaaS platform for a bank in Charlotte, you don’t want to rewrite this logic everywhere.

I always recommend creating a custom hook called useComponentSize.

This keeps your components clean and adheres to the DRY (Don’t Repeat Yourself) principle.

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

// Custom Hook
function useComponentHeight() {
  const [height, setHeight] = useState(0);
  const ref = useRef(null);

  useLayoutEffect(() => {
    const handleResize = () => {
      if (ref.current) {
        setHeight(ref.current.getBoundingClientRect().height);
      }
    };

    handleResize(); // Set initial height

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return [ref, height];
}

// Implementation
const TaxForm = () => {
  const [formRef, formHeight] = useComponentHeight();

  const formStyle = {
    maxWidth: '500px',
    margin: '40px auto',
    padding: '30px',
    boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
    borderRadius: '12px'
  };

  return (
    <div style={{ fontFamily: 'Segoe UI' }}>
      <div ref={formRef} style={formStyle}>
        <h2>IRS Form 1040 - Simplified</h2>
        <label>Full Name:</label><br/>
        <input type="text" style={{ width: '100%', marginBottom: '10px' }} /><br/>
        <label>SSN (Last 4 Digits):</label><br/>
        <input type="password" style={{ width: '100%', marginBottom: '10px' }} /><br/>
        <label>Total Income:</label><br/>
        <input type="number" placeholder="$0.00" style={{ width: '100%' }} />
      </div>
      <p style={{ textAlign: 'center' }}>
        Form Visual Height: <strong>{formHeight.toFixed(2)}px</strong>
      </p>
    </div>
  );
};

export default TaxForm;

You can see the output in the screenshot below.

How to Get Component Height in React

The getBoundingClientRect() method is slightly different from offsetHeight.

It returns a fractional value (e.g., 300.45px) which is more precise for high-resolution displays used by many professionals today.

Key Differences Between Measurement Properties

In my experience, developers often get confused about which property to use. Here is a quick breakdown:

  • clientHeight: Includes padding but not borders, margins, or scrollbars.
  • offsetHeight: Includes padding, borders, and the scrollbar (if any).
  • scrollHeight: The total height of the content, including what is hidden behind a scrollbar.

If you are trying to calculate the total size for a container to avoid scrolling, scrollHeight is your best friend.

Deal with Images and Heights

A classic mistake I made early in my career was measuring a component before the images inside it had finished loading.

If your React component contains images (like a product gallery), the height will initially be small and then “pop” once the image downloads.

To fix this, you should either provide fixed dimensions for your images or use the onLoad event of the image to trigger a re-measurement of the parent height.

Performance Considerations

Whenever you use ResizeObserver or resize a window, you are executing code frequently.

For a simple app, this isn’t an issue. However, if you have 50 components all measuring themselves at once, you might see a performance dip.

In those scenarios, I usually wrap the height update in a “debounce” function to ensure it only updates every 100ms or so.

This is a trick I used while optimizing a data-heavy dashboard for a logistics firm in Seattle to keep the UI smooth on older laptops.

In this tutorial, we looked at several ways to get the height of a React component, from basic refs to dynamic observers.

Measuring DOM elements is a common task, and knowing which method to use can save you hours of debugging layout issues.

I hope you found this guide helpful and can use these code snippets in your next project.

You may also like to read:

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.