Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 5 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ function useResizeObserver<T extends HTMLElement>(opts?: {

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

function useResizeObserver<T>(
opts: {
ref?: RefObject<T>;
ref?: RefObject<T> | null;
onResize?: ResizeHandler;
} = {}
): { ref: RefObject<T> } & ObservedSize {
Expand Down Expand Up @@ -69,7 +69,7 @@ function useResizeObserver<T>(
});

useEffect(() => {
if (resizeObserverRef.current) {
if (!(ref?.current instanceof Element) || resizeObserverRef.current) {
return;
}

Expand Down Expand Up @@ -103,14 +103,10 @@ function useResizeObserver<T>(
}
}
});
}, []);
});
Copy link
Author

@GreenGremlin GreenGremlin Jul 21, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing the dependency array is necessary, in case ref is passed as null, then later passed as a valid value. This should not affect performance though, because the effect bails once the observer is created.


useEffect(() => {
if (
typeof ref !== "object" ||
ref === null ||
!(ref.current instanceof Element)
) {
if (!(ref?.current instanceof Element)) {
return;
}

Expand Down
30 changes: 30 additions & 0 deletions tests/basic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,36 @@ describe("Vanilla tests", () => {
handler.assertSize({ width: 100, height: 200 });
});

it("should not initialize a ResizeObserver if no ref is passed", async () => {
spyOn(window, "ResizeObserver");
const Test: FunctionComponent<HandlerResolverComponentProps> = ({
resolveHandler,
}) => {
const { width, height } = useResizeObserver({ ref: null });
const currentSizeRef = useRef<{
width: number | undefined;
height: number | undefined;
}>({ width: undefined, height: undefined });
currentSizeRef.current.height = height;
currentSizeRef.current.width = width;

useEffect(() => {
resolveHandler(createComponentHandler({ currentSizeRef }));
}, []);

return (
<div style={{ width: 100, height: 200 }}>
{width}x{height}
</div>
);
};

await render(Test);

await delay(50);
expect(window.ResizeObserver).not.toHaveBeenCalled();
});

it("should be able to reuse the same ref to measure different elements", async () => {
let switchRefs = (): void => {
throw new Error(`"switchRefs" should've been implemented by now.`);
Expand Down