Skip to content

Commit

Permalink
Hook useMeasure replaces useSize.
Browse files Browse the repository at this point in the history
  • Loading branch information
loriensleafs committed Mar 5, 2019
1 parent 138c96a commit e5ef3ea
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/hooks/useMeasure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useEffect, useMemo, useReducer, useRef } from 'react';
import ResizeObserver from 'resize-observer-polyfill';

const reducer = (state, rect) => (rect ? rect : state);

export default function useMeasure(refProp) {
const ref = refProp ? refProp : useRef();
const [rect, dispatch] = useReducer(reducer, {
x: 0,
y: 0,
width: 0,
height: 0,
top: 0,
right: 0,
bottom: 0,
left: 0,
});
const observer = useMemo(
() =>
new ResizeObserver(([entry]) =>
dispatch(entry.contentRect.toJSON()),
),
[],
);

useEffect(() => {
if (ref.current) {
observer.observe(ref.current);
dispatch(ref.current.getBoundingClientRect().toJSON());
return () => observer.disconnect;
}
}, []);

return [rect, ref];
}

0 comments on commit e5ef3ea

Please sign in to comment.