Skip to content

Commit

Permalink
Add tests for useDeepMemo
Browse files Browse the repository at this point in the history
  • Loading branch information
jassmith committed Jan 26, 2024
1 parent 7f4e351 commit 66f7390
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
3 changes: 1 addition & 2 deletions packages/core/src/common/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,5 @@ export function useDeepMemo<T>(value: T): T {
ref.current = value;
}

// eslint-disable-next-line react-hooks/exhaustive-deps
return React.useMemo(() => ref.current, [ref.current]);
return ref.current;
}
41 changes: 41 additions & 0 deletions packages/core/test/use-deep-memo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { renderHook, cleanup } from "@testing-library/react-hooks";
import { useDeepMemo } from "../src/common/utils.js";
import { expect, describe, it, afterEach } from "vitest";

describe("useDeepMemo", () => {
afterEach(cleanup);

it("returns the initial value", () => {
const initialValue = { a: 1 };
const { result } = renderHook(() => useDeepMemo(initialValue));
expect(result.current).toEqual(initialValue);
});

it("updates the value on deep change", () => {
const initialValue = { a: 1 };
const changedValue = { a: 2 };
const { result, rerender } = renderHook(({ value }) => useDeepMemo(value), {
initialProps: { value: initialValue },
});

expect(result.current).toEqual(initialValue);

// Change the value deeply
rerender({ value: changedValue });
expect(result.current).toEqual(changedValue);
});

it("does not update the value on shallow/no change", () => {
const initialValue = { a: 1 };
const sameValue = { a: 1 };
const { result, rerender } = renderHook(({ value }) => useDeepMemo(value), {
initialProps: { value: initialValue },
});

expect(result.current).toEqual(initialValue);

// Re-render with the same value (shallow change)
rerender({ value: sameValue });
expect(result.current).toEqual(initialValue);
});
});

0 comments on commit 66f7390

Please sign in to comment.