Skip to content
Merged
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
2 changes: 1 addition & 1 deletion gitbook/reactjrx/bindings/react/useobserve.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ interface Options<T, DefaultValue> {
* `source`: An observable, a function returning one, or `undefined`. Pass a stable observable directly: the hook subscribes to it again when its reference changes. Otherwise pass a function with `deps`, so the observable is only created again when a dependency changes. With `undefined`, nothing is observed and the default value is returned.
* **optional** `options`:
* `defaultValue`: returned until the source emits its first value. A `BehaviorSubject`, or any source that emits synchronously when subscribed, doesn't need it: its value is there on the first render.
* `compareFn`: tells whether a new value equals the previous one. An equal value doesn't re-render. Defaults to strict equality (`===`). Pass `isShallowEqual` (exported by reactjrx), or your own function, to compare objects by content.
* `compareFn`: tells whether a new value equals the previous one. An equal value doesn't re-render. Defaults to strict equality (`===`). Pass [isShallowEqual](../../utils/javascript/isshallowequal.md) (exported by reactjrx) to compare own enumerable properties one level deep, or your own function for a different equality rule. `isShallowEqual` does not compare the contents of `Date`, `Map` or `Set` objects.
* **optional** `deps`: The values the function depends on. When one of them changes (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), the function is called again and its observable replaces the previous one.

### Returns
Expand Down
10 changes: 9 additions & 1 deletion gitbook/reactjrx/utils/javascript/isshallowequal.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# isShallowEqual

Returns true when two values are equal one level deep: the same primitive, or two objects with the same `constructor` and the same own enumerable string keys holding `===` values. Symbol and non-enumerable properties are not compared.
Returns true when two values are equal one level deep: primitives compared with `Object.is`, or two objects with the same `constructor` and the same own enumerable string keys holding `Object.is`-equal values. Objects with a null prototype and objects with an own `hasOwnProperty` key are supported. Symbol and non-enumerable properties are not compared.

### Usage

Expand All @@ -9,10 +9,18 @@ import { isShallowEqual } from "reactjrx"

isShallowEqual({ a: 1, b: "x" }, { a: 1, b: "x" }) // true
isShallowEqual({ a: { b: 1 } }, { a: { b: 1 } }) // false, `a` holds two different objects
isShallowEqual({ a: NaN }, { a: NaN }) // true
isShallowEqual(0, -0) // false
```

Pass it as the `compareFn` of [useObserve](../../bindings/react/useobserve.md) to skip the render of a new object that holds the same values.

### Comparison semantics

`NaN` compares equal to `NaN`, and positive and negative zero compare as different values. If your application treats both zero signs as the same value, normalize them to `0` before comparison, or pass a custom `compareFn`.

This is a shallow comparison of enumerable properties, not a comparison of built-in object contents. Two `Date` objects with different timestamps or two `Map` or `Set` objects with different entries can compare equal because they have the same constructor and no own enumerable string keys. Use a comparator that checks their contents when those differences matter.

### Reference

```typescript
Expand Down
56 changes: 56 additions & 0 deletions src/lib/binding/useObserve/useObserve.compare.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,62 @@ it("should not return new value when the hook re-render but the value is the sam
})

describe("given a custom compareFn", () => {
it("keeps null-prototype emissions live and only renders changed values", () => {
const initial = Object.assign(Object.create(null), { x: 1 })
const source$ = new BehaviorSubject<Record<string, number>>(initial)
const values: UseObserveResult<
Record<string, number>,
Record<string, number>
>[] = []
const { result } = renderHook(() => {
const value = useObserve(source$, { compareFn: isShallowEqual })
useEffect(() => {
values.push(value)
}, [value])
return value
})

act(() => {
source$.next(Object.assign(Object.create(null), { x: 1 }))
})
expect(values).toHaveLength(1)
expect(result.current.error).toBeUndefined()
expect(result.current.observableState).toBe("live")

act(() => {
source$.next(Object.assign(Object.create(null), { x: 2 }))
})
expect(values).toHaveLength(2)
expect(result.current.data?.x).toBe(2)
expect(result.current.error).toBeUndefined()
})

it("deduplicates NaN properties while delivering signed-zero changes", () => {
const source$ = new BehaviorSubject({ x: Number.NaN })
const values: Array<{ x: number } | undefined> = []
const { result } = renderHook(() => {
const value = useObserve(source$, { compareFn: isShallowEqual })
useEffect(() => {
values.push(value.data)
}, [value])
return value
})

act(() => {
source$.next({ x: Number.NaN })
})
expect(values).toHaveLength(1)

act(() => {
source$.next({ x: 0 })
})
act(() => {
source$.next({ x: -0 })
})
expect(values).toHaveLength(3)
expect(result.current.data?.x).toBe(-0)
})

it("should re-render when the object is same but new reference", async () => {
const values: Array<{ a: string } | undefined> = []
const source$ = new BehaviorSubject({ a: "a" })
Expand Down
54 changes: 54 additions & 0 deletions src/lib/utils/shallowEqual.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ describe("shallowEqual", () => {
expect(isShallowEqual(null, undefined)).toBe(false)
})

it("compares a null-prototype object with null", () => {
const value = Object.create(null)
expect(isShallowEqual(value, null)).toBe(false)
expect(isShallowEqual(null, value)).toBe(false)
})

it("returns true for two string values that are equal", () => {
expect(isShallowEqual("hello", "hello")).toBe(true)
})
Expand Down Expand Up @@ -66,4 +72,52 @@ describe("shallowEqual", () => {
const obj2 = "hello"
expect(isShallowEqual(obj1, obj2)).toBe(false)
})

it("compares null-prototype dictionaries by their own keys", () => {
const a = Object.assign(Object.create(null), { x: 1 })
const b = Object.assign(Object.create(null), { x: 1 })
expect(isShallowEqual(a, b)).toBe(true)
b.x = 2
expect(isShallowEqual(a, b)).toBe(false)
})

it("handles an own property named hasOwnProperty", () => {
expect(isShallowEqual({ hasOwnProperty: 1 }, { hasOwnProperty: 1 })).toBe(
true,
)
expect(isShallowEqual({ hasOwnProperty: 1 }, { hasOwnProperty: 2 })).toBe(
false,
)
})

it("does not mistake inherited keys for own keys", () => {
const b = Object.assign(Object.create({ x: 1 }), { y: 1 })
expect(isShallowEqual({ x: 1 }, b)).toBe(false)
})

it("considers NaN equal to itself and to another NaN property", () => {
expect(isShallowEqual(Number.NaN, Number.NaN)).toBe(true)
expect(isShallowEqual({ x: Number.NaN }, { x: Number.NaN })).toBe(true)
expect(
isShallowEqual({ constructor: Number.NaN }, { constructor: Number.NaN }),
).toBe(true)
})

it("distinguishes positive and negative zero", () => {
expect(isShallowEqual(0, -0)).toBe(false)
expect(isShallowEqual(-0, 0)).toBe(false)
expect(isShallowEqual({ x: 0 }, { x: -0 })).toBe(false)
expect(isShallowEqual({ x: -0 }, { x: -0 })).toBe(true)
})

it("keeps different constructors distinct", () => {
expect(isShallowEqual(Object.create(null), {})).toBe(false)
expect(isShallowEqual([], {})).toBe(false)
})

it("compares nested objects by reference", () => {
const value = { x: 1 }
expect(isShallowEqual({ value }, { value })).toBe(true)
expect(isShallowEqual({ value }, { value: { x: 1 } })).toBe(false)
})
})
26 changes: 15 additions & 11 deletions src/lib/utils/shallowEqual.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
export function isShallowEqual<A, B>(objA: A, objB: B): boolean {
// Check if both objects are null or undefined
if (objA === null || objA === undefined || objB === undefined) {
// biome-ignore lint/suspicious/noExplicitAny: TODO
return (objA as any) === (objB as any)
// Return early if either value is null or undefined
if (
objA === null ||
objB === null ||
objA === undefined ||
objB === undefined
) {
Comment on lines +3 to +8

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

The objB === null check also fixes a second crash, and no test covers it. On main, isShallowEqual(Object.create(null), null) throws TypeError: Cannot convert undefined or null to object. Could you add a regression test to shallowEqual.test.ts?

it("compares a null-prototype object with null", () => {
  expect(isShallowEqual(Object.create(null), null)).toBe(false)
})

Generated by Claude Code

return Object.is(objA, objB)
}

// Check if both objects are primitives
if (typeof objA !== "object" || typeof objB !== "object") {
// biome-ignore lint/suspicious/noExplicitAny: TODO
return (objA as any) === (objB as any)
return Object.is(objA, objB)
}

// Check if both objects have the same prototype
if (objA.constructor !== objB?.constructor) {
// Check if both objects have the same constructor
if (!Object.is(objA.constructor, objB.constructor)) {
return false
}

Expand All @@ -26,9 +29,10 @@ export function isShallowEqual<A, B>(objA: A, objB: B): boolean {

// Check if the values of the keys are equal
for (const key of keysA) {
// biome-ignore lint/suspicious/noPrototypeBuiltins: TODO
// biome-ignore lint/suspicious/noExplicitAny: TODO
if (!objB.hasOwnProperty(key) || objA[key] !== (objB as any)[key]) {
if (
!Object.hasOwn(objB, key) ||
!Object.is(objA[key], (objB as Record<keyof A, unknown>)[key])
) {
return false
}
}
Expand Down
Loading