react-sizeme vs react-measure vs react-resize-aware
React Resize Detection Libraries Comparison
1 Year
react-sizemereact-measurereact-resize-awareSimilar Packages:
What's React Resize Detection Libraries?

React resize detection libraries provide developers with tools to monitor changes in the dimensions of components in a React application. These libraries facilitate responsive design by allowing components to adapt to size changes, whether due to window resizing or dynamic content changes. They help ensure that UI elements render correctly across different screen sizes and orientations, enhancing user experience and accessibility.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
react-sizeme797,8131,952-324 years agoMIT
react-measure377,0091,943-304 years agoMIT
react-resize-aware23,93957032 kB0a year agoMIT
Feature Comparison: react-sizeme vs react-measure vs react-resize-aware

Measurement Capabilities

  • react-sizeme:

    react-sizeme offers a simple API for size detection, providing the dimensions of the component in a straightforward manner. It abstracts the complexity of measurement, making it easy to use for developers who want quick results without detailed metrics.

  • react-measure:

    react-measure provides detailed measurement capabilities, allowing you to access both width and height of components. It can handle complex scenarios where precise dimensions are necessary, making it suitable for applications with intricate layouts.

  • react-resize-aware:

    react-resize-aware focuses primarily on detecting size changes rather than providing detailed measurements. It informs you when a component's size changes, but does not give specific width or height values, making it less suitable for cases requiring precise measurements.

Performance

  • react-sizeme:

    react-sizeme is also lightweight and focuses on providing a simple interface for size detection. Its performance is generally good, but it may not be as optimized for heavy-duty applications as react-measure.

  • react-measure:

    react-measure is designed to efficiently handle size changes, but it may introduce some overhead due to its detailed measurement capabilities. It is optimized for performance, but in scenarios with frequent size changes, it could impact rendering speed if not managed properly.

  • react-resize-aware:

    react-resize-aware is lightweight and optimized for performance, making it an excellent choice for applications that require minimal overhead. It efficiently detects size changes without the need for complex calculations, ensuring smooth performance even in dynamic layouts.

Ease of Use

  • react-sizeme:

    react-sizeme is designed for simplicity and ease of use. Its intuitive API allows developers to get started quickly, making it an excellent choice for those who want to implement size detection with minimal effort.

  • react-measure:

    react-measure has a steeper learning curve due to its comprehensive feature set. Developers may need to invest time to understand how to effectively utilize its measurement capabilities and integrate it into their components.

  • react-resize-aware:

    react-resize-aware is easy to implement and requires minimal setup. Its straightforward API allows developers to quickly integrate size detection into their components without extensive documentation or learning.

Use Cases

  • react-sizeme:

    react-sizeme is versatile and can be used in various applications, especially where quick size detection is needed without complex requirements. It is suitable for responsive designs and components that need to adjust based on their size.

  • react-measure:

    react-measure is ideal for applications that require detailed layout management, such as dashboards, complex grids, or any UI that needs precise control over dimensions. It is well-suited for scenarios where components need to adapt based on their exact size.

  • react-resize-aware:

    react-resize-aware is best for simpler applications where you only need to know when a component's size changes, such as responsive layouts or basic UI adjustments. It is effective for cases where detailed measurements are not necessary.

Community and Support

  • react-sizeme:

    react-sizeme benefits from a growing community and decent documentation. While it may not have as many resources as react-measure, it is still actively maintained and provides sufficient support for developers.

  • react-measure:

    react-measure has a strong community and good documentation, making it easier for developers to find support and examples. Its popularity ensures that it is regularly maintained and updated with new features.

  • react-resize-aware:

    react-resize-aware has a smaller community compared to react-measure, but it is still well-documented. Support may be more limited, but the simplicity of the library reduces the need for extensive troubleshooting.

How to Choose: react-sizeme vs react-measure vs react-resize-aware
  • react-sizeme:

    Select react-sizeme if you want a straightforward API that abstracts away the complexity of resize detection. It is suitable for developers who prioritize ease of use and want to quickly implement size detection in their components without dealing with the intricacies of measuring dimensions.

  • react-measure:

    Choose react-measure if you need a comprehensive solution that provides detailed measurement capabilities, including the ability to measure both width and height of elements and respond to changes in size dynamically. It is particularly useful for complex layouts where precise measurements are critical.

  • react-resize-aware:

    Opt for react-resize-aware if you prefer a lightweight solution that focuses on detecting size changes without additional overhead. This package is ideal for simple use cases where you want to trigger re-renders based on size changes without the need for extensive measurement capabilities.

README for react-sizeme

 

Make your React Components aware of their width and/or height!

 

npm MIT License Travis Codecov

  • Hyper Responsive Components!
  • Performant.
  • Easy to use.
  • Extensive browser support.
  • Supports functional and class Component types.
  • Tiny bundle size.
  • Demo: https://4mkpc.csb.app/

Use it via the render prop pattern (supports children or render prop):

import { SizeMe } from 'react-sizeme'

function MyApp() {
  return <SizeMe>{({ size }) => <div>My width is {size.width}px</div>}</SizeMe>
}

Or, via a higher order component:

import { withSize } from 'react-sizeme'

function MyComponent({ size }) {
  return <div>My width is {size.width}px</div>
}

export default withSize()(MyComponent)

 


TOCs

 


Intro

Give your Components the ability to have render logic based on their height and/or width. Responsive design on the Component level. This allows you to create highly reusable components that can adapt to wherever they are rendered.

Check out a working demo here: https://4mkpc.csb.app/

 


Installation

Firstly, ensure you have the required peer dependencies:

npm install react react-dom

Note: We require >=react@0.14.0 and >=react-dom@0.14.0

npm install react-sizeme

 


Configuration

The following configuration options are available. Please see the usage docs for how to pass these configuration values into either the component or higher order function.

  • monitorWidth (boolean, default: true)

    If true, then any changes to your Components rendered width will cause an recalculation of the "size" prop which will then be be passed into your Component.

  • monitorHeight (boolean, default: false)

    If true, then any changes to your Components rendered height will cause an recalculation of the "size" prop which will then be be passed into your Component.

    PLEASE NOTE: that this is set to false by default

  • refreshRate (number, default: 16)

    The maximum frequency, in milliseconds, at which size changes should be recalculated when changes in your Component's rendered size are being detected. This should not be set to lower than 16.

  • refreshMode (string, default: 'throttle')

    The mode in which refreshing should occur. Valid values are "debounce" and "throttle".

    "throttle" will eagerly measure your component and then wait for the refreshRate to pass before doing a new measurement on size changes.

    "debounce" will wait for a minimum of the refreshRate before it does a measurement check on your component.

    "debounce" can be useful in cases where your component is animated into the DOM.

    NOTE: When using "debounce" mode you may want to consider disabling the placeholder as this adds an extra delay in the rendering time of your component.

  • noPlaceholder (boolean, default: false)

    By default we render a "placeholder" component initially so we can try and "prefetch" the expected size for your component. This is to avoid any unnecessary deep tree renders. If you feel this is not an issue for your component case and you would like to get an eager render of your component then disable the placeholder using this config option.

    NOTE: You can set this globally. See the docs on first render.

 


Component Usage

We provide a "render props pattern" based component. You can import it like so:

import { SizeMe } from 'react-sizeme'

You then provide it either a render or children prop containing a function/component that will receive a size prop (an object with width and height properties):

<SizeMe>{({ size }) => <div>My width is {size.width}px</div>}</SizeMe>

or

<SizeMe render={({ size }) => <div>My width is {size.width}px</div>} />

To provide configuration you simply add any customisation as props. For example:

<SizeMe
  monitorHeight
  refreshRate={32}
  render={({ size }) => <div>My width is {size.width}px</div>}
/>

 


HOC Usage

We provide you with a higher order component function called withSize. You can import it like so:

import { withSize } from 'react-sizeme'

Firstly, you have to call the withSize function, passing in an optional configuration object should you wish to customise the behaviour:

const withSizeHOC = withSize()

You can then use the returned Higher Order Component to decorate any of your existing Components with the size awareness ability:

const SizeAwareComponent = withSizeHOC(MyComponent)

Your component will then receive a size prop (an object with width and height properties).

Note that the values could be undefined based on the configuration you provided (e.g. you explicitly do not monitor either of the dimensions)

Below is a full example:

import { withSize } from 'react-sizeme'

class MyComponent extends Component {
  render() {
    const { width, height } = this.props.size

    return (
      <div>
        My size is {width || -1}px x {height || -1}px
      </div>
    )
  }
}

export default withSize({ monitorHeight: true })(MyComponent)

onSize callback alternative usage

The higher order component also allows an alternative usage where you provide an onSize callback function.

This allows the "parent" to manage the size value rather than your component, which can be useful in specific circumstances.

Below is an example of it's usage.

Firstly, create a component you wish to know the size of:

import { withSize } from 'react-sizeme'

function MyComponent({ message }) {
  return <div>{message}</div>
}

export default withSize()(MyComponent)

Now create a "parent" component providing it a onSize callback function to the size aware component:

class ParentComponent extends React.Component {
  onSize = (size) => {
    console.log('MyComponent has a width of', size.width)
  }

  render() {
    return <MyComponent message="Hello world" onSize={this.onSize} />
  }
}

 


Under the hood

It can be useful to understand the rendering workflow should you wish to debug any issues we may be having.

In order to size your component we have a bit of a chicken/egg scenario. We can't know the width/height of your Component until it is rendered. This can lead wasteful rendering cycles should you choose to render your components based on their width/height.

Therefore for the first render of your component we actually render a lightweight placeholder in place of your component in order to obtain the width/height. If your component was being passed a className or style prop then these will be applied to the placeholder so that it can more closely resemble your actual components dimensions.

So the first dimensions that are passed to your component may not be "correct" dimensions, however, it should quickly receive the "correct" dimensions upon render.

Should you wish to avoid the render of a placeholder and have an eager render of your component then you can use the noPlaceholder configuration option. Using this configuration value your component will be rendered directly, however, the size prop may contain undefined for width and height until your component completes its first render.

 


Examples

Loading different child components based on size

import React from 'react'
import LargeChildComponent from './LargeChildComponent'
import SmallChildComponent from './SmallChildComponent'
import sizeMe from 'react-sizeme'

function MyComponent(props) {
  const { width, height } = props.size

  const ToRenderChild = height > 600 ? LargeChildComponent : SmallChildComponent

  return (
    <div>
      <h1>
        My size is {width}x{height}
      </div>
      <ToRenderChild />
    </div>
  )
}

export default sizeMe({ monitorHeight: true })(MyComponent)

EXTRA POINTS! Combine the above with a code splitting API (e.g. Webpack's System.import) to avoid unnecessary code downloads for your clients. Zing!

 


Server Side Rendering

Okay, I am gonna be up front here and tell you that using this library in an SSR context is most likely a bad idea. If you insist on doing so you then you should take the time to make yourself fully aware of any possible repercussions you application may face.

A standard sizeMe configuration involves the rendering of a placeholder component. After the placeholder is mounted to the DOM we extract it's dimension information and pass it on to your actual component. We do this in order to avoid any unnecessary render cycles for possibly deep component trees. Whilst this is useful for a purely client side set up, this is less than useful for an SSR context as the delivered page will contain empty placeholders. Ideally you want actual content to be delivered so that users without JS can still have an experience, or SEO bots can scrape your website.

To avoid the rendering of placeholders in this context you can make use of the noPlaceholders global configuration value. Setting this flag will disables any placeholder rendering. Instead your wrapped component will be rendered directly - however it's initial render will contain no values within the size prop (i.e. width, and height will be null).

import sizeMe from 'react-sizeme'

// This is a global variable. i.e. will be the default for all instances.
sizeMe.noPlaceholders = true

Note: if you only partialy server render your application you may want to use the component level configuration that allows disabling placeholders per component (e.g. sizeMe({ noPlaceholder: true }))

It is up to you to decide how you would like to initially render your component then. When your component is sent to the client and mounted to the DOM SizeMe will calculate and send the dimensions to your component as normal. I suggest you tread very carefully with how you use this updated information and do lots of testing using various screen dimensions. Try your best to avoid unnecessary re-rendering of your components, for the sake of your users.

If you come up with any clever strategies for this please do come share them with us! :)

 


Extreme Appreciation!

We make use of the awesome element-resize-detector library. This library makes use of an scroll/object based event strategy which outperforms window resize event listening dramatically. The original idea for this approach comes from another library, namely css-element-queries by Marc J. Schmidt. I recommend looking into these libraries for history, specifics, and more examples. I love them for the work they did, whithout which this library would not be possible. :sparkling_heart:

 


Backers

Thank goes to all our backers! [Become a backer].