Skip to content

Commit 99646c6

Browse files
committed
Allow bypassing the observer...by not passing a ref option
1 parent 9656441 commit 99646c6

File tree

2 files changed

+35
-9
lines changed

2 files changed

+35
-9
lines changed

src/index.ts

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,13 @@ function useResizeObserver<T extends HTMLElement>(opts?: {
2121

2222
// Type definition when the hook just passes through the user provided ref.
2323
function useResizeObserver<T extends HTMLElement>(opts?: {
24-
ref: RefObject<T>;
24+
ref: RefObject<T> | null;
2525
onResize?: ResizeHandler;
2626
}): { ref: RefObject<T> } & ObservedSize;
2727

2828
function useResizeObserver<T>(
2929
opts: {
30-
ref?: RefObject<T>;
30+
ref?: RefObject<T> | null;
3131
onResize?: ResizeHandler;
3232
} = {}
3333
): { ref: RefObject<T> } & ObservedSize {
@@ -69,7 +69,7 @@ function useResizeObserver<T>(
6969
});
7070

7171
useEffect(() => {
72-
if (resizeObserverRef.current) {
72+
if (!(ref?.current instanceof Element) || resizeObserverRef.current) {
7373
return;
7474
}
7575

@@ -103,14 +103,10 @@ function useResizeObserver<T>(
103103
}
104104
}
105105
});
106-
}, []);
106+
});
107107

108108
useEffect(() => {
109-
if (
110-
typeof ref !== "object" ||
111-
ref === null ||
112-
!(ref.current instanceof Element)
113-
) {
109+
if (!(ref?.current instanceof Element)) {
114110
return;
115111
}
116112

tests/basic.tsx

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,36 @@ describe("Vanilla tests", () => {
145145
handler.assertSize({ width: 100, height: 200 });
146146
});
147147

148+
it("should not initialize a ResizeObserver if no ref is passed", async () => {
149+
spyOn(window, "ResizeObserver");
150+
const Test: FunctionComponent<HandlerResolverComponentProps> = ({
151+
resolveHandler,
152+
}) => {
153+
const { width, height } = useResizeObserver({ ref: null });
154+
const currentSizeRef = useRef<{
155+
width: number | undefined;
156+
height: number | undefined;
157+
}>({ width: undefined, height: undefined });
158+
currentSizeRef.current.height = height;
159+
currentSizeRef.current.width = width;
160+
161+
useEffect(() => {
162+
resolveHandler(createComponentHandler({ currentSizeRef }));
163+
}, []);
164+
165+
return (
166+
<div style={{ width: 100, height: 200 }}>
167+
{width}x{height}
168+
</div>
169+
);
170+
};
171+
172+
await render(Test);
173+
174+
await delay(50);
175+
expect(window.ResizeObserver).not.toHaveBeenCalled();
176+
});
177+
148178
it("should be able to reuse the same ref to measure different elements", async () => {
149179
let switchRefs = (): void => {
150180
throw new Error(`"switchRefs" should've been implemented by now.`);

0 commit comments

Comments
 (0)