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