MCPcopy Create free account
hub / github.com/QuarkGluonPlasma/react-course-code / useSize

Function useSize

ahooks-hook/src/useSize.ts:6–36  ·  view source on GitHub ↗
(targetRef: RefObject<HTMLElement>)

Source from the content-addressed store, hash-verified

4type Size = { width: number; height: number };
5
6function useSize(targetRef: RefObject<HTMLElement>): Size | undefined {
7
8 const [state, setState] = useState<Size | undefined>(
9 () => {
10 const el = targetRef.current;
11 return el ? { width: el.clientWidth, height: el.clientHeight } : undefined
12 },
13 );
14
15 useEffect(() => {
16 const el = targetRef.current;
17
18 if (!el) {
19 return;
20 }
21
22 const resizeObserver = new ResizeObserver((entries) => {
23 entries.forEach((entry) => {
24 const { clientWidth, clientHeight } = entry.target;
25 setState({ width: clientWidth, height: clientHeight });
26 });
27 });
28 resizeObserver.observe(el);
29
30 return () => {
31 resizeObserver.disconnect();
32 };
33 }, []);
34
35 return state;
36}
37
38export default useSize;

Callers 1

App2.tsxFile · 0.85

Calls 3

useStateFunction · 0.90
useEffectFunction · 0.90
setStateFunction · 0.50

Tested by

no test coverage detected