Skip to content

Commit

Permalink
fix: properly cleanup useQueries* on unmount
Browse files Browse the repository at this point in the history
With React 18 and strict mode enabled, each component ist rendered twice
This caused the hooks to unsubscribe but not resubscribe.
  • Loading branch information
andipaetzold committed Feb 11, 2023
1 parent 3b94bc0 commit b77becc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
11 changes: 10 additions & 1 deletion src/internal/useMultiListen.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ describe("changing size", () => {
]);
});

it("decreate", () => {
it("decrease", () => {
const { result, rerender } = renderHook(({ refs }) => useMultiListen(refs, onChange, isEqual), {
initialProps: { refs: [refA1, refB1] },
});
Expand All @@ -119,6 +119,7 @@ describe("changing size", () => {
]);

rerender({ refs: [refA1] });
expect(onChangeUnsubscribe).toHaveBeenCalledTimes(1);
expect(result.current).toStrictEqual([[result1, false, undefined]]);

act(() => setValue1(result3));
Expand Down Expand Up @@ -183,3 +184,11 @@ it("should return emitted error", () => {
[undefined, false, error2],
]);
});

it("unmount", () => {
const { unmount } = renderHook(() => useMultiListen([refA1, refB1], onChange, isEqual));

unmount();

expect(onChangeUnsubscribe).toHaveBeenCalledTimes(2);
});
12 changes: 10 additions & 2 deletions src/internal/useMultiListen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,16 @@ export function useMultiListen<Value, Error, Reference>(
}
}, [references]);

// // unsubscribe on unmount
useEffect(() => () => subscriptions.current.forEach((unsubscribe) => unsubscribe()), []);
// unsubscribe and cleanup on unmount
useEffect(
() => () => {
subscriptions.current.forEach((unsubscribe) => unsubscribe());
subscriptions.current = [];

prevReferences.current = [];
},
[]
);

return useMemo(
() => states.map((state) => [state.value, state.loading, state.error] as ValueHookResult<Value, Error>),
Expand Down

0 comments on commit b77becc

Please sign in to comment.