open-amdocs / webrix

Powerful building blocks for React-based web applications
https://webrix.amdocs.com
Apache License 2.0
432 stars 32 forks source link

useDimensions: Support a custom callback #118

Open yairEO opened 1 year ago

yairEO commented 1 year ago

https://github.com/open-amdocs/webrix/blob/master/src/hooks/useDimensions/useDimensions.js


For devs who need to use a resizeObserver (without caring for the return value of the hook):

export default (ref, callback) => {
    const [dimensions, setDimensions] = useState({width: 0, height: 0});
    const observer = useRef(new ResizeObserver(entries => {
        callback?.(entries);
        setDimensions(readResizeObserverEntry(entries[0]));
    }));
    useEffect(() => {
        const {current: obs} = observer;
        obs.observe(ref.current);
        return () => obs.disconnect();
    }, [ref]);
    return dimensions;
};

This would allow using this same hook for other purposes also (as it already handling its own cleanup)