-
Notifications
You must be signed in to change notification settings - Fork 43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
use 'resize observer' #36
Comments
Here's a hook implemented with export function useDimensions<T extends HTMLElement>(): [
MutableRefObject<any>,
DOMRectReadOnly | null
] {
const ref = useRef<T>(null);
const [dimensions, setDimensions] = useState<DOMRectReadOnly | null>(null);
const resizeObserver = new ResizeObserver(([entry]) =>
setDimensions(entry.contentRect)
);
useEffect(() => {
const current = ref.current; // enclose current so the reference can be used in the unsubscribe
if (current) {
resizeObserver.observe(current);
return () => resizeObserver.unobserve(current);
}
return undefined;
}, [ref.current]);
return [ref, dimensions];
} |
hooks should not declare useRef, they should receive ref from outside. |
My 2 cents implementation version of this: const useDimensions = (domNode) => {
const [dimensions, setDimensions] = React.useState();
React.useEffect(() => {
const resizeObserver = new ResizeObserver(([entry]) =>
setDimensions(entry.contentRect)
);
if (domNode) {
resizeObserver.observe(domNode);
return () => resizeObserver.unobserve(domNode);
}
return undefined;
}, [domNode]);
return dimensions;
}; usable as const Component = ()=>{
// ...
const [parentNode, setParentNode] = React.useState();
const { width = 960, height = 500 } = useDimensions(parentNode) ?? {};
// ...
return (
<div ref={setParentNode}>children content</div>
)
} related explanation on what and why:
|
In the past I've used resize observer to detect size changes. I think it can also be used in this hook.
Results can also be debounces to ensure good performance.
You can also use this polyfill for compatibility with older browsers.
The text was updated successfully, but these errors were encountered: