-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathuseGridDimensions.ts
More file actions
38 lines (29 loc) · 1.12 KB
/
useGridDimensions.ts
File metadata and controls
38 lines (29 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { useLayoutEffect, useRef, useState } from 'react';
import { flushSync } from 'react-dom';
export function useGridDimensions() {
const gridRef = useRef<HTMLDivElement>(null);
const [inlineSize, setInlineSize] = useState(1);
const [blockSize, setBlockSize] = useState(1);
useLayoutEffect(() => {
const { ResizeObserver } = window;
// don't break in Node.js (SSR), jsdom, and browsers that don't support ResizeObserver
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (ResizeObserver == null) return;
const { clientWidth, clientHeight } = gridRef.current!;
setInlineSize(clientWidth);
setBlockSize(clientHeight);
const resizeObserver = new ResizeObserver((entries) => {
const size = entries[0].contentBoxSize[0];
// we use flushSync here to avoid flashing scrollbars
flushSync(() => {
setInlineSize(size.inlineSize);
setBlockSize(size.blockSize);
});
});
resizeObserver.observe(gridRef.current!);
return () => {
resizeObserver.disconnect();
};
}, []);
return [gridRef, inlineSize, blockSize] as const;
}