$ show react-component/resize-observer
This is a small, focused React component library that wraps the native ResizeObserver API. It provides a declarative component (`<ResizeObserver>`) that can observe a single child element for size changes, supporting both direct children and render-prop patterns for cases where the observed element is not the immediate child. A `Collection` component uses React context and microtask batching to aggregate multiple resize events from child observers into a single callback, improving performance when many elements are observed. The library also exports a `useResizeObserver` hook for imperative use. Internally, it manages a single shared `ResizeObserver` instance with a map of element-to-callback sets, ensuring efficient resource usage. The code is clean, well-typed, and properly tested, making it a reliable building block for responsive UIs. As part of the Ant Design ecosystem, it follows established patterns and integrates smoothly with other @rc-component packages.
The LLM identified 3 files worth highlighting for reuse:
Implements a global ResizeObserver that manages a Map of element-to-callback Sets. This pattern avoids creating multiple ResizeObserver instances, which is more efficient and avoids browser limits. The `observe` and `unobserve` functions are self-contained and can be extracted for any project needing a centralized ResizeObserver manager. The module also exports `_el` and `_rs` for testability.
A custom React hook that encapsulates the logic of attaching a ResizeObserver to an element, detecting actual size changes (including offset dimensions), and calling both synchronous and deferred callbacks. It uses `useEvent` from `@rc-component/util` to maintain stable callback references without stale closures. The hook handles dynamic targets (functions vs. direct refs) and can be extracted for reuse in other React projects needing to observe element resize.
Provides a `Collection` component that uses React context to collect resize events from descendant `ResizeObserver` components. It batches them within a microtask (via `Promise.resolve().then(...)`) and fires a single `onBatchResize` callback with an array of resize info, including custom `data` payloads. This pattern is reusable for any scenario where multiple similar events need to be aggregated before triggering a side effect, reducing callback frequency.