{"name":"react-resize-detector","version":"12.2.0","keywords":["react","resize","detector","resizeObserver","observer"],"author":{"url":"https://github.com/maslianok","name":"Vitalii Maslianok","email":"maslianok@gmail.com"},"license":"MIT","_id":"react-resize-detector@12.2.0","maintainers":[{"name":"maslianok","email":"maslianok@gmail.com"},{"name":"snelsi","email":"npm@snelsi.com"}],"contributors":[{"url":"@james_womack","name":"James J. Womack"},{"url":"@snelsi","name":"Roman Zhuravlov"}],"homepage":"https://github.com/maslianok/react-resize-detector","bugs":{"url":"https://github.com/maslianok/react-resize-detector/issues"},"dist":{"shasum":"b5986ee5687fe3436bbb118eba9209f68a7cf3c7","tarball":"http://registry-npm.ywwl.com/react-resize-detector/download/react-resize-detector-12.2.0.tgz","fileCount":13,"integrity":"sha512-NrsddLjv3zQ3dg4Xh6KNH/GuCbD6sS6kfWlI+DfFp+5Wa2rRoVZ9gR8H4MumsYRun4H9BME2tb1jk/KUkUNV6Q==","signatures":[{"sig":"MEUCIQD36/xYyY9dZlkEg0LpAQA/R6i7q0VRNwIG3jzHirC0ZQIgLJEhNE3RjFZhVVQHT2a/Sk2AYUEDqRl46XEoVhlAS0Y=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":41128,"size":10846,"noattachment":false,"key":"/react-resize-detector/-/react-resize-detector-12.2.0.tgz"},"type":"module","types":"./build/index.d.ts","exports":"./build/index.js","gitHead":"61b4529d757c4ffec577df48f8e236277bdffa0c","scripts":{"fix":"npm run prettier && npm run lint","lint":"eslint . --fix","build":"rollup -c","prebuild":"tsc","prettier":"prettier --write .","prerelease":"npm version prerelease --preid=rc","prepublishOnly":"npm run build"},"_npmUser":{"name":"maslianok","email":"maslianok@gmail.com"},"repository":{"url":"git+https://github.com/maslianok/react-resize-detector.git","type":"git"},"_npmVersion":"11.4.2","description":"React resize detector","directories":{},"sideEffects":false,"_nodeVersion":"24.3.0","dependencies":{"lodash":"^4.17.21"},"_hasShrinkwrap":false,"devDependencies":{"tslib":"^2.8.1","eslint":"^9.28.0","rollup":"^4.42.0","prettier":"^3.5.3","@eslint/js":"^9.28.0","typescript":"^5.8.3","@types/react":"^19.1.7","@types/lodash":"^4.17.17","@types/react-dom":"^19.1.6","typescript-eslint":"^8.34.0","eslint-plugin-react":"^7.37.5","eslint-config-prettier":"^10.1.5","@rollup/plugin-commonjs":"^28.0.3","@rollup/plugin-typescript":"^12.1.2","@rollup/plugin-node-resolve":"^16.0.1","rollup-plugin-node-externals":"^8.0.0"},"peerDependencies":{"react":"^18.0.0 || ^19.0.0"},"_npmOperationalInternal":{"tmp":"tmp/react-resize-detector_12.2.0_1756324499989_0.3319023717880587","host":"s3://npm-registry-packages-npm-production"},"readme":"# Handle element resizes like it's 2025!\r\n\r\n<img src=\"https://img.shields.io/npm/v/react-resize-detector?style=flat-square\" /> <img src=\"https://img.shields.io/npm/l/react-resize-detector?style=flat-square\" /> <img src=\"https://img.shields.io/npm/dm/react-resize-detector?style=flat-square\" /> <img src=\"https://img.shields.io/bundlejs/size/react-resize-detector?style=flat-square\" />\r\n\r\n#### [Live demo](https://react-resize-detector.vercel.app/)\r\n\r\nModern browsers now have native support for detecting element size changes through [ResizeObservers](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver). This library utilizes ResizeObservers to facilitate managing element size changes in React applications.\r\n\r\n🐥 Tiny <a href=\"https://bundlephobia.com/result?p=react-resize-detector\" target=\"__blank\">~2kb</a>\r\n\r\n🐼 Written in TypeScript\r\n\r\n🐠 Used by <a href=\"https://github.com/maslianok/react-resize-detector/network/dependents\" target=\"__blank\">170k repositories</a>\r\n\r\n🦄 Produces <a href=\"https://npmtrends.com/react-resize-detector\" target=\"__blank\">100 million downloads annually</a>\r\n\r\nNo `window.resize` listeners! No timeouts!\r\n\r\n## Should you use this library?\r\n\r\n**Consider CSS Container Queries first!** They now work in [all major browsers](https://caniuse.com/css-container-queries) and might solve your use case with pure CSS.\r\n\r\n<details><summary>CSS Container Queries Example</summary>\r\n\r\n```html\r\n<div class=\"post\">\r\n  <div class=\"card\">\r\n    <h2>Card title</h2>\r\n    <p>Card content</p>\r\n  </div>\r\n</div>\r\n```\r\n\r\n```css\r\n.post {\r\n  container-type: inline-size;\r\n}\r\n\r\n/* Default heading styles for the card title */\r\n.card h2 {\r\n  font-size: 1em;\r\n}\r\n\r\n/* If the container is larger than 700px */\r\n@container (min-width: 700px) {\r\n  .card h2 {\r\n    font-size: 2em;\r\n  }\r\n}\r\n```\r\n\r\n</details>\r\n\r\n**Use this library when you need:**\r\n\r\n- JavaScript-based resize logic with full TypeScript support\r\n- Complex calculations based on dimensions\r\n- Integration with React state/effects\r\n- Programmatic control over resize behavior\r\n\r\n## Installation\r\n\r\n```bash\r\nnpm install react-resize-detector\r\n# OR\r\nyarn add react-resize-detector\r\n# OR\r\npnpm add react-resize-detector\r\n```\r\n\r\n## Quick Start\r\n\r\n### Basic Usage\r\n\r\n```tsx\r\nimport { useResizeDetector } from 'react-resize-detector';\r\n\r\nconst CustomComponent = () => {\r\n  const { width, height, ref } = useResizeDetector<HTMLDivElement>();\r\n  return <div ref={ref}>{`${width}x${height}`}</div>;\r\n};\r\n```\r\n\r\n### With Resize Callback\r\n\r\n```tsx\r\nimport { useCallback } from 'react';\r\nimport { useResizeDetector, OnResizeCallback } from 'react-resize-detector';\r\n\r\nconst CustomComponent = () => {\r\n  const onResize: OnResizeCallback = useCallback((payload) => {\r\n    if (payload.width !== null && payload.height !== null) {\r\n      console.log('Dimensions:', payload.width, payload.height);\r\n    } else {\r\n      console.log('Element unmounted');\r\n    }\r\n  }, []);\r\n\r\n  const { width, height, ref } = useResizeDetector<HTMLDivElement>({\r\n    onResize,\r\n  });\r\n\r\n  return <div ref={ref}>{`${width}x${height}`}</div>;\r\n};\r\n```\r\n\r\n### With External Ref (Advanced)\r\n\r\n_It's not advised to use this approach, as dynamically mounting and unmounting the observed element could lead to unexpected behavior._\r\n\r\n```tsx\r\nimport { useRef } from 'react';\r\nimport { useResizeDetector } from 'react-resize-detector';\r\n\r\nconst CustomComponent = () => {\r\n  const targetRef = useRef<HTMLDivElement>(null);\r\n  const { width, height } = useResizeDetector({ targetRef });\r\n  return <div ref={targetRef}>{`${width}x${height}`}</div>;\r\n};\r\n```\r\n\r\n## API Reference\r\n\r\n### Hook Signature\r\n\r\n```typescript\r\nuseResizeDetector<T extends HTMLElement = HTMLElement>(\r\n  props?: useResizeDetectorProps<T>\r\n): UseResizeDetectorReturn<T>\r\n```\r\n\r\n### Props\r\n\r\n| Prop              | Type                                        | Description                                                                                                           | Default     |\r\n| ----------------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ----------- |\r\n| `onResize`        | `(payload: ResizePayload) => void`          | Callback invoked with resize information                                                                              | `undefined` |\r\n| `handleWidth`     | `boolean`                                   | Trigger updates on width changes                                                                                      | `true`      |\r\n| `handleHeight`    | `boolean`                                   | Trigger updates on height changes                                                                                     | `true`      |\r\n| `skipOnMount`     | `boolean`                                   | Skip the first resize event when component mounts                                                                     | `false`     |\r\n| `disableRerender` | `boolean`                                   | Disable re-renders triggered by the hook. Only the onResize callback will be called                                   | `false`     |\r\n| `refreshMode`     | `'throttle' \\| 'debounce'`                  | Rate limiting strategy. See [es-toolkit docs](https://es-toolkit.dev)                                                 | `undefined` |\r\n| `refreshRate`     | `number`                                    | Delay in milliseconds for rate limiting                                                                               | `1000`      |\r\n| `refreshOptions`  | `{ leading?: boolean; trailing?: boolean }` | Additional options for throttle/debounce                                                                              | `undefined` |\r\n| `observerOptions` | `ResizeObserverOptions`                     | Options passed to [`resizeObserver.observe`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver/observe) | `undefined` |\r\n| `targetRef`       | `MutableRefObject<T \\| null>`               | External ref to observe (use with caution)                                                                            | `undefined` |\r\n\r\n## Advanced Examples\r\n\r\n### Responsive Component\r\n\r\n```jsx\r\nimport { useResizeDetector } from 'react-resize-detector';\r\n\r\nconst ResponsiveCard = () => {\r\n  const { width, ref } = useResizeDetector();\r\n\r\n  const cardStyle = {\r\n    padding: width > 600 ? '2rem' : '1rem',\r\n    fontSize: width > 400 ? '1.2em' : '1em',\r\n    flexDirection: width > 500 ? 'row' : 'column',\r\n  };\r\n\r\n  return (\r\n    <div ref={ref} style={cardStyle}>\r\n      <h2>Responsive Card</h2>\r\n      <p>Width: {width}px</p>\r\n    </div>\r\n  );\r\n};\r\n```\r\n\r\n### Chart Resizing\r\n\r\n```jsx\r\nimport { useResizeDetector } from 'react-resize-detector';\r\nimport { useEffect, useRef } from 'react';\r\n\r\nconst Chart = () => {\r\n  const chartRef = useRef(null);\r\n  const { width, height, ref } = useResizeDetector({\r\n    refreshMode: 'debounce',\r\n    refreshRate: 100,\r\n  });\r\n\r\n  useEffect(() => {\r\n    if (width && height && chartRef.current) {\r\n      // Redraw chart with new dimensions\r\n      redrawChart(chartRef.current, width, height);\r\n    }\r\n  }, [width, height]);\r\n\r\n  return <canvas ref={ref} />;\r\n};\r\n```\r\n\r\n### Performance Optimization\r\n\r\n```jsx\r\nimport { useResizeDetector } from 'react-resize-detector';\r\n\r\nconst OptimizedComponent = () => {\r\n  const { width, height, ref } = useResizeDetector({\r\n    // Only track width changes\r\n    handleHeight: false,\r\n    // Debounce rapid changes\r\n    refreshMode: 'debounce',\r\n    refreshRate: 150,\r\n    // Skip initial mount calculation\r\n    skipOnMount: true,\r\n    // Use border-box for more accurate measurements\r\n    observerOptions: { box: 'border-box' },\r\n  });\r\n\r\n  return <div ref={ref}>Optimized: {width}px wide</div>;\r\n};\r\n```\r\n\r\n### Disable Re-renders\r\n\r\n```jsx\r\nimport { useResizeDetector } from 'react-resize-detector';\r\n\r\nconst NonRerenderingComponent = () => {\r\n  const { ref } = useResizeDetector({\r\n    // Disable re-renders triggered by the hook\r\n    disableRerender: true,\r\n    // Handle resize events through callback only\r\n    onResize: ({ width, height }) => {\r\n      // Update external state or perform side effects\r\n      // without causing component re-renders\r\n      console.log('Resized to:', width, height);\r\n    },\r\n  });\r\n\r\n  return <div ref={ref}>This component won't re-render on resize</div>;\r\n};\r\n```\r\n\r\n## Browser Support\r\n\r\n- ✅ Chrome 64+\r\n- ✅ Firefox 69+\r\n- ✅ Safari 13.1+\r\n- ✅ Edge 79+\r\n\r\nFor older browsers, consider using a [ResizeObserver polyfill](https://github.com/que-etc/resize-observer-polyfill).\r\n\r\n## Testing\r\n\r\n```jsx\r\nconst { ResizeObserver } = window;\r\n\r\nbeforeEach(() => {\r\n  delete window.ResizeObserver;\r\n  // Mock ResizeObserver for tests\r\n  window.ResizeObserver = jest.fn().mockImplementation(() => ({\r\n    observe: jest.fn(),\r\n    unobserve: jest.fn(),\r\n    disconnect: jest.fn(),\r\n  }));\r\n});\r\n\r\nafterEach(() => {\r\n  window.ResizeObserver = ResizeObserver;\r\n  jest.restoreAllMocks();\r\n});\r\n```\r\n\r\n## Performance Tips\r\n\r\n1. **Use `handleWidth`/`handleHeight: false`** if you only need one dimension\r\n2. **Enable `skipOnMount: true`** if you don't need initial measurements\r\n3. **Use `debounce` or `throttle`** for expensive resize handlers\r\n4. **Specify `observerOptions.box`** for consistent measurements\r\n\r\n## License\r\n\r\nMIT\r\n\r\n## ❤️ Support\r\n\r\nShow us some love and STAR ⭐ the project if you find it useful\r\n","publish_time":1756324500217,"_cnpm_publish_time":1756324500217,"dist-tags":{"beta":"12.1.0-beta.0","latest":"12.3.0"}}