{"id":18488328,"url":"https://github.com/ZeeCoder/use-resize-observer","last_synced_at":"2025-04-08T20:33:04.896Z","repository":{"id":39706265,"uuid":"155022429","full_name":"ZeeCoder/use-resize-observer","owner":"ZeeCoder","description":" A React hook that allows you to use a ResizeObserver to measure an element's size.","archived":false,"fork":false,"pushed_at":"2023-08-08T17:50:31.000Z","size":1025,"stargazers_count":641,"open_issues_count":6,"forks_count":41,"subscribers_count":5,"default_branch":"master","last_synced_at":"2024-09-08T16:51:49.136Z","etag":null,"topics":["container-query","css-in-js","measure","react","react-hook","reactjs","resize","resizeobserver","size"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ZeeCoder.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null},"funding":{"github":"ZeeCoder","patreon":"zeecoder"}},"created_at":"2018-10-28T00:42:09.000Z","updated_at":"2024-09-07T11:45:37.000Z","dependencies_parsed_at":"2023-01-29T08:46:23.440Z","dependency_job_id":"47f9342e-9701-4a03-9c28-c2ec64decf99","html_url":"https://github.com/ZeeCoder/use-resize-observer","commit_stats":{"total_commits":124,"total_committers":5,"mean_commits":24.8,"dds":0.4838709677419355,"last_synced_commit":"b2592d85284ddbfe98af6023a2a4238f97ecabc1"},"previous_names":[],"tags_count":27,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZeeCoder%2Fuse-resize-observer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZeeCoder%2Fuse-resize-observer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZeeCoder%2Fuse-resize-observer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZeeCoder%2Fuse-resize-observer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ZeeCoder","download_url":"https://codeload.github.com/ZeeCoder/use-resize-observer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223343866,"owners_count":17129954,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["container-query","css-in-js","measure","react","react-hook","reactjs","resize","resizeobserver","size"],"created_at":"2024-11-06T12:51:34.280Z","updated_at":"2025-04-08T20:33:04.889Z","avatar_url":"https://github.com/ZeeCoder.png","language":"TypeScript","readme":"# use-resize-observer\n\n\n\u003ch1 align=\"center\"\u003e\n\t\u003cbr\u003e\n\t\u003cimg width=\"250\" src=\"https://raw.githubusercontent.com/ZeeCoder/use-resize-observer/master/media/Logo.png\" alt=\"useResizeObserver\"\u003e\n\t\u003cbr\u003e\n    \u003cbr\u003e\n\u003c/h1\u003e\n\nA React hook that allows you to use a ResizeObserver to measure an element's size.\n\n[![npm version](https://badge.fury.io/js/use-resize-observer.svg)](https://npmjs.com/package/use-resize-observer)\n[![build](https://github.com/ZeeCoder/use-resize-observer/workflows/Testing/badge.svg)](https://github.com/ZeeCoder/use-resize-observer/actions/workflows/testing.yml)\n[![BrowserStack Status](https://automate.browserstack.com/badge.svg?badge_key=aVpjV2RZbThnWnh2S0FvREh0cGRtRHRCNzYwUmw4N0Z4WUxybHM0WkpqST0tLW9RT0tDeGk3OVU2WkNtalpON29xWFE9PQ==--ec6a97c52cd7ad30417612ca3f5df511eef5d631)](https://automate.browserstack.com/public-build/aVpjV2RZbThnWnh2S0FvREh0cGRtRHRCNzYwUmw4N0Z4WUxybHM0WkpqST0tLW9RT0tDeGk3OVU2WkNtalpON29xWFE9PQ==--ec6a97c52cd7ad30417612ca3f5df511eef5d631)\n\n## Highlights\n\n- Written in **TypeScript**.\n- **Tiny**: [648B](.size-limit.json) (minified, gzipped) Monitored by [size-limit](https://github.com/ai/size-limit).\n- Exposes an **onResize callback** if you need more control.\n- `box` [option](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver/observe#syntax).\n- Works with **SSR**.\n- Works with **CSS-in-JS**.\n- **Supports custom refs** in case you [had one already](#passing-in-your-own-ref).\n- **Uses RefCallback by default** To address delayed mounts and changing ref elements.\n- **Ships a polyfilled version**\n- Handles many edge cases you might not even think of.\n  (See this documentation and the test cases.)\n- Easy to compose ([Throttle / Debounce](#throttle--debounce), [Breakpoints](#breakpoints))\n- **Tested in real browsers** (Currently latest Chrome, Firefox, Edge, Safari, Opera, IE 11, iOS and Android, sponsored by BrowserStack)\n\n## In Action\n\n[CodeSandbox Demo](https://codesandbox.io/s/nrp0w2r5z0)\n\n## Install\n\n```sh\nyarn add use-resize-observer --dev\n# or\nnpm install use-resize-observer --save-dev\n```\n\n## Options\n\n| Option   | Type                                                                                 | Description                                                                                                                   | Default        |\n| -------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | -------------- |\n| ref      | undefined \u0026#124; RefObject \u0026#124; HTMLElement                                        | A ref or element to observe.                                                                                                  | undefined      |\n| box      | undefined \u0026#124; \"border-box\" \u0026#124; \"content-box\" \u0026#124; \"device-pixel-content-box\" | The [box model](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver/observe#syntax) to use for observation.       | \"content-box\"  |\n| onResize | undefined \u0026#124; ({ width?: number, height?: number }) =\u003e void                       | A callback receiving the element size. If given, then the hook will not return the size, and instead will call this callback. | undefined      |\n| round    | undefined \u0026#124; (n: number) =\u003e number                                               | A function to use for rounding values instead of the default.                                                                 | `Math.round()` |\n\n## Response\n\n| Name   | Type                    | Description                                    |\n| ------ | ----------------------- | ---------------------------------------------- |\n| ref    | RefCallback             | A callback to be passed to React's \"ref\" prop. |\n| width  | undefined \u0026#124; number | The width (or \"inlineSize\") of the element.     |\n| height | undefined \u0026#124; number | The height (or \"blockSize\") of the element.   |\n\n## Basic Usage\n\nNote that the default builds are not polyfilled! For instructions and alternatives,\nsee the [Transpilation / Polyfilling](#transpilation--polyfilling) section.\n\n```tsx\nimport React from \"react\";\nimport useResizeObserver from \"use-resize-observer\";\n\nconst App = () =\u003e {\n  const { ref, width = 1, height = 1 } = useResizeObserver\u003cHTMLDivElement\u003e();\n\n  return (\n    \u003cdiv ref={ref}\u003e\n      Size: {width}x{height}\n    \u003c/div\u003e\n  );\n};\n```\n\nTo observe a different box size other than content box, pass in the `box` option, like so:\n\n```tsx\nconst { ref, width, height } = useResizeObserver\u003cHTMLDivElement\u003e({\n  box: \"border-box\",\n});\n```\n\nNote that if the browser does not support the given box type, then the hook won't report any sizes either.\n\n### Box Options\n\nNote that box options are experimental, and as such are not supported by all browsers that implemented ResizeObservers. (See [here](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry).)\n\n`content-box` (default)\n\nSafe to use by all browsers that implemented ResizeObservers. The hook internally will fall back to `contentRect` from\nthe old spec in case `contentBoxSize` is not available.\n\n`border-box`\n\nSupported well for the most part by evergreen browsers. If you need to support older versions of these browsers however,\nthen you may want to feature-detect for support, and optionally include a polyfill instead of the native implementation.\n\n`device-pixel-content-box`\n\nSurma has a [very good article](https://web.dev/device-pixel-content-box/) on how this allows us to do pixel perfect\nrendering. At the time of writing, however this has very limited support.\nThe advices on feature detection for `border-box` apply here too.\n\n### Custom Rounding\n\nBy default this hook passes the measured values through `Math.round()`, to avoid re-rendering on every subpixel changes.\n\nIf this is not what you want, then you can provide your own function:\n\n**Rounding Down Reported Values**\n\n```tsx\nconst { ref, width, height } = useResizeObserver\u003cHTMLDivElement\u003e({\n  round: Math.floor,\n});\n```\n\n**Skipping Rounding**\n\n```tsx\nimport React from \"react\";\nimport useResizeObserver from \"use-resize-observer\";\n\n// Outside the hook to ensure this instance does not change unnecessarily.\nconst noop = (n) =\u003e n;\n\nconst App = () =\u003e {\n  const {\n    ref,\n    width = 1,\n    height = 1,\n  } = useResizeObserver\u003cHTMLDivElement\u003e({ round: noop });\n\n  return (\n    \u003cdiv ref={ref}\u003e\n      Size: {width}x{height}\n    \u003c/div\u003e\n  );\n};\n```\n\nNote that the round option is sensitive to the function reference, so make sure you either use `useCallback`\nor declare your rounding function outside of the hook's function scope, if it does not rely on any hook state.\n(As shown above.)\n\n### Getting the Raw Element from the Default `RefCallback`\n\nNote that \"ref\" in the above examples is a `RefCallback`, not a `RefObject`, meaning you won't be\nable to access \"ref.current\" if you need the element itself.\n\nTo get the raw element, either you use your own RefObject (see later in this doc),\nor you can merge the returned ref with one of your own:\n\n```tsx\nimport React, { useCallback, useEffect, useRef } from \"react\";\nimport useResizeObserver from \"use-resize-observer\";\nimport mergeRefs from \"react-merge-refs\";\n\nconst App = () =\u003e {\n  const { ref, width = 1, height = 1 } = useResizeObserver\u003cHTMLDivElement\u003e();\n\n  const mergedCallbackRef = mergeRefs([\n    ref,\n    (element: HTMLDivElement) =\u003e {\n      // Do whatever you want with the `element`.\n    },\n  ]);\n\n  return (\n    \u003cdiv ref={mergedCallbackRef}\u003e\n      Size: {width}x{height}\n    \u003c/div\u003e\n  );\n};\n```\n\n## Passing in Your Own `ref`\n\nYou can pass in your own ref instead of using the one provided.\nThis can be useful if you already have a ref you want to measure.\n\n```ts\nconst ref = useRef\u003cHTMLDivElement\u003e(null);\nconst { width, height } = useResizeObserver\u003cHTMLDivElement\u003e({ ref });\n```\n\nYou can even reuse the same hook instance to measure different elements:\n\n[CodeSandbox Demo](https://codesandbox.io/s/use-resize-observer-reusing-refs-buftd)\n\n## Measuring a raw element\n\nThere might be situations where you have an element already that you need to measure.\n`ref` now accepts elements as well, not just refs, which means that you can do this:\n\n```ts\nconst { width, height } = useResizeObserver\u003cHTMLDivElement\u003e({\n  ref: divElement,\n});\n```\n\n## Using a Single Hook to Measure Multiple Refs\n\nThe hook reacts to ref changes, as it resolves it to an element to observe.\nThis means that you can freely change the custom `ref` option from one ref to\nanother and back, and the hook will start observing whatever is set in its options.\n\n## Opting Out of (or Delaying) ResizeObserver Instantiation\n\nIn certain cases you might want to delay creating a ResizeObserver instance.\n\nYou might provide a library, that only optionally provides observation features\nbased on props, which means that while you have the hook within your component,\nyou might not want to actually initialise it.\n\nAnother example is that you might want to entirely opt out of initialising, when\nyou run some tests, where the environment does not provide the `ResizeObserver`.\n\n([See discussions](https://github.com/ZeeCoder/use-resize-observer/issues/40))\n\nYou can do one of the following depending on your needs:\n\n- Use the default `ref` RefCallback, or provide a custom ref conditionally,\n  only when needed. The hook will not create a ResizeObserver instance up until\n  there's something there to actually observe.\n- Patch the test environment, and make a polyfill available as the ResizeObserver.\n  (This assumes you don't already use the polyfilled version, which would switch\n  to the polyfill when no native implementation was available.)\n\n## The \"onResize\" Callback\n\nBy the default the hook will trigger a re-render on all changes to the target\nelement's width and / or height.\n\nYou can opt out of this behaviour, by providing an `onResize` callback function,\nwhich'll simply receive the width and height of the element when it changes, so\nthat you can decide what to do with it:\n\n```tsx\nimport React from \"react\";\nimport useResizeObserver from \"use-resize-observer\";\n\nconst App = () =\u003e {\n  // width / height will not be returned here when the onResize callback is present\n  const { ref } = useResizeObserver\u003cHTMLDivElement\u003e({\n    onResize: ({ width, height }) =\u003e {\n      // do something here.\n    },\n  });\n\n  return \u003cdiv ref={ref} /\u003e;\n};\n```\n\nThis callback also makes it possible to implement your own hooks that report only\nwhat you need, for example:\n\n- Reporting only width or height\n- Throttle / debounce\n- Wrap in `requestAnimationFrame`\n\n## Hook Composition\n\nAs this hook intends to remain low-level, it is encouraged to build on top of it via hook composition, if additional features are required.\n\n### Throttle / Debounce\n\nYou might want to receive values less frequently than changes actually occur.\n\n[CodeSandbox Demo](https://codesandbox.io/s/use-resize-observer-throttle-and-debounce-8uvsg)\n\n### Breakpoints\n\nAnother popular concept are breakpoints. Here is an example for a simple hook accomplishing that.\n\n[CodeSandbox Demo](https://codesandbox.io/s/use-resize-observer-breakpoints-3hiv8)\n\n## Defaults (SSR)\n\nOn initial mount the ResizeObserver will take a little time to report on the\nactual size.\n\nUntil the hook receives the first measurement, it returns `undefined` for width\nand height by default.\n\nYou can override this behaviour, which could be useful for SSR as well.\n\n```ts\nconst { ref, width = 100, height = 50 } = useResizeObserver\u003cHTMLDivElement\u003e();\n```\n\nHere \"width\" and \"height\" will be 100 and 50 respectively, until the\nResizeObserver kicks in and reports the actual size.\n\n## Without Defaults\n\nIf you only want real measurements (only values from the ResizeObserver without\nany default values), then you can just leave defaults off:\n\n```ts\nconst { ref, width, height } = useResizeObserver\u003cHTMLDivElement\u003e();\n```\n\nHere \"width\" and \"height\" will be undefined until the ResizeObserver takes its\nfirst measurement.\n\n## Container/Element Query with CSS-in-JS\n\nIt's possible to apply styles conditionally based on the width / height of an\nelement using a CSS-in-JS solution, which is the basic idea behind\ncontainer/element queries:\n\n[CodeSandbox Demo](https://codesandbox.io/s/use-resize-observer-container-query-with-css-in-js-iitxl)\n\n## Transpilation / Polyfilling\n\nBy default the library provides transpiled ES5 modules in CJS / ESM module formats.\n\nPolyfilling is recommended to be done in the host app, and not within imported\nlibraries, as that way consumers have control over the exact polyfills being used.\n\nThat said, there's a [polyfilled](https://github.com/juggle/resize-observer)\nCJS module that can be used for convenience:\n\n```ts\nimport useResizeObserver from \"use-resize-observer/polyfilled\";\n```\n\nNote that using the above will use the polyfill, [even if the native ResizeObserver is available](https://github.com/juggle/resize-observer#basic-usage).\n\nTo use the polyfill as a fallback only when the native RO is unavailable, you can polyfill yourself instead,\neither in your app's entry file, or you could create a local `useResizeObserver` module, like so:\n\n```ts\n// useResizeObserver.ts\nimport { ResizeObserver } from \"@juggle/resize-observer\";\nimport useResizeObserver from \"use-resize-observer\";\n\nif (!window.ResizeObserver) {\n  window.ResizeObserver = ResizeObserver;\n}\n\nexport default useResizeObserver;\n```\n\nThe same technique can also be used to provide any of your preferred ResizeObserver polyfills out there.\n\n## Related\n\n- [@zeecoder/container-query](https://github.com/ZeeCoder/container-query)\n- [@zeecoder/react-resize-observer](https://github.com/ZeeCoder/react-resize-observer)\n\n## License\n\nMIT\n","funding_links":["https://github.com/sponsors/ZeeCoder","https://patreon.com/zeecoder"],"categories":["TypeScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FZeeCoder%2Fuse-resize-observer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FZeeCoder%2Fuse-resize-observer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FZeeCoder%2Fuse-resize-observer/lists"}