@livestore/react 0.3.0-dev.10 → 0.3.0-dev.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/LiveStoreContext.d.ts +5 -3
  3. package/dist/LiveStoreContext.d.ts.map +1 -1
  4. package/dist/LiveStoreContext.js +7 -3
  5. package/dist/LiveStoreContext.js.map +1 -1
  6. package/dist/LiveStoreProvider.js +2 -17
  7. package/dist/LiveStoreProvider.js.map +1 -1
  8. package/dist/__tests__/fixture.d.ts +6 -8
  9. package/dist/__tests__/fixture.d.ts.map +1 -1
  10. package/dist/__tests__/fixture.js +6 -7
  11. package/dist/__tests__/fixture.js.map +1 -1
  12. package/dist/experimental/components/LiveList.d.ts +2 -2
  13. package/dist/experimental/components/LiveList.d.ts.map +1 -1
  14. package/dist/experimental/components/LiveList.js +5 -4
  15. package/dist/experimental/components/LiveList.js.map +1 -1
  16. package/dist/mod.d.ts +0 -1
  17. package/dist/mod.d.ts.map +1 -1
  18. package/dist/mod.js +0 -1
  19. package/dist/mod.js.map +1 -1
  20. package/dist/useAtom.d.ts +4 -2
  21. package/dist/useAtom.d.ts.map +1 -1
  22. package/dist/useAtom.js +32 -28
  23. package/dist/useAtom.js.map +1 -1
  24. package/dist/useQuery.d.ts +26 -3
  25. package/dist/useQuery.d.ts.map +1 -1
  26. package/dist/useQuery.js +60 -45
  27. package/dist/useQuery.js.map +1 -1
  28. package/dist/useQuery.test.js +70 -16
  29. package/dist/useQuery.test.js.map +1 -1
  30. package/dist/useRcRef.d.ts +72 -0
  31. package/dist/useRcRef.d.ts.map +1 -0
  32. package/dist/useRcRef.js +146 -0
  33. package/dist/useRcRef.js.map +1 -0
  34. package/dist/useRcRef.test.d.ts +2 -0
  35. package/dist/useRcRef.test.d.ts.map +1 -0
  36. package/dist/useRcRef.test.js +128 -0
  37. package/dist/useRcRef.test.js.map +1 -0
  38. package/dist/useRcResource.d.ts +76 -0
  39. package/dist/useRcResource.d.ts.map +1 -0
  40. package/dist/useRcResource.js +150 -0
  41. package/dist/useRcResource.js.map +1 -0
  42. package/dist/useRcResource.test.d.ts +2 -0
  43. package/dist/useRcResource.test.d.ts.map +1 -0
  44. package/dist/useRcResource.test.js +122 -0
  45. package/dist/useRcResource.test.js.map +1 -0
  46. package/dist/useRow.d.ts +10 -7
  47. package/dist/useRow.d.ts.map +1 -1
  48. package/dist/useRow.js +16 -19
  49. package/dist/useRow.js.map +1 -1
  50. package/dist/useRow.test.js +62 -80
  51. package/dist/useRow.test.js.map +1 -1
  52. package/dist/useScopedQuery.d.ts +10 -4
  53. package/dist/useScopedQuery.d.ts.map +1 -1
  54. package/dist/useScopedQuery.js +96 -52
  55. package/dist/useScopedQuery.js.map +1 -1
  56. package/dist/useScopedQuery.test.js +13 -12
  57. package/dist/useScopedQuery.test.js.map +1 -1
  58. package/package.json +6 -6
  59. package/src/LiveStoreContext.ts +10 -6
  60. package/src/LiveStoreProvider.tsx +1 -17
  61. package/src/__snapshots__/useQuery.test.tsx.snap +2011 -0
  62. package/src/__snapshots__/useRow.test.tsx.snap +335 -140
  63. package/src/__tests__/fixture.tsx +6 -9
  64. package/src/experimental/components/LiveList.tsx +8 -7
  65. package/src/mod.ts +0 -1
  66. package/src/useAtom.ts +22 -11
  67. package/src/useQuery.test.tsx +165 -67
  68. package/src/useQuery.ts +84 -54
  69. package/src/useRcResource.test.tsx +167 -0
  70. package/src/useRcResource.ts +180 -0
  71. package/src/useRow.test.tsx +73 -107
  72. package/src/useRow.ts +32 -35
  73. package/src/useScopedQuery.test.tsx +0 -96
  74. package/src/useScopedQuery.ts +0 -143
@@ -0,0 +1,167 @@
1
+ import * as ReactTesting from '@testing-library/react'
2
+ import * as React from 'react'
3
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
4
+
5
+ import { __resetUseRcResourceCache, useRcResource } from './useRcResource.js'
6
+
7
+ describe.each([{ strictMode: true }, { strictMode: false }])('useRcResource (strictMode=%s)', ({ strictMode }) => {
8
+ beforeEach(() => {
9
+ __resetUseRcResourceCache()
10
+ })
11
+
12
+ const wrapper = strictMode ? React.StrictMode : React.Fragment
13
+
14
+ it('should create a stateful entity using make and call cleanup on unmount', () => {
15
+ const makeSpy = vi.fn(() => Symbol('statefulResource'))
16
+ const cleanupSpy = vi.fn()
17
+
18
+ const { result, unmount } = ReactTesting.renderHook(() => useRcResource('key-1', makeSpy, cleanupSpy), { wrapper })
19
+
20
+ expect(makeSpy).toHaveBeenCalledTimes(1)
21
+ expect(result.current).toBeDefined()
22
+
23
+ expect(cleanupSpy).toHaveBeenCalledTimes(0)
24
+ unmount()
25
+ expect(cleanupSpy).toHaveBeenCalledTimes(1)
26
+ })
27
+
28
+ it('should reuse the same entity when the key remains unchanged', () => {
29
+ const makeSpy = vi.fn(() => Symbol('statefulResource'))
30
+ const cleanupSpy = vi.fn()
31
+
32
+ const { result, rerender, unmount } = ReactTesting.renderHook(
33
+ ({ key }) => useRcResource(key, makeSpy, cleanupSpy),
34
+ { initialProps: { key: 'consistent-key' }, wrapper },
35
+ )
36
+
37
+ const instance1 = result.current
38
+
39
+ // Re-render with the same key
40
+ rerender({ key: 'consistent-key' })
41
+ const instance2 = result.current
42
+
43
+ expect(instance1).toBe(instance2)
44
+ expect(makeSpy).toHaveBeenCalledTimes(1)
45
+
46
+ unmount()
47
+ expect(cleanupSpy).toHaveBeenCalledTimes(1)
48
+ })
49
+
50
+ it('should dispose the previous instance when the key changes', () => {
51
+ const makeSpy = vi.fn(() => Symbol('statefulResource'))
52
+ const cleanupSpy = vi.fn()
53
+
54
+ const { result, rerender, unmount } = ReactTesting.renderHook(
55
+ ({ key }) => useRcResource(key, makeSpy, cleanupSpy),
56
+ { initialProps: { key: 'a' }, wrapper },
57
+ )
58
+
59
+ const instanceA = result.current
60
+
61
+ // Change the key; this should trigger the disposal of the 'a' instance
62
+ rerender({ key: 'b' })
63
+ const instanceB = result.current
64
+
65
+ expect(instanceA).not.toBe(instanceB)
66
+ expect(makeSpy).toHaveBeenCalledTimes(2)
67
+ expect(cleanupSpy).toHaveBeenCalledTimes(1)
68
+
69
+ unmount()
70
+ expect(cleanupSpy).toHaveBeenCalledTimes(2)
71
+ })
72
+
73
+ it('should not dispose the entity until all consumers unmount', () => {
74
+ const makeSpy = vi.fn(() => Symbol('statefulResource'))
75
+ const cleanupSpy = vi.fn()
76
+
77
+ // Simulate two consumers using the same key independently.
78
+ const { unmount: unmount1 } = ReactTesting.renderHook(() => useRcResource('shared-key', makeSpy, cleanupSpy), {
79
+ wrapper,
80
+ })
81
+ const { unmount: unmount2, result } = ReactTesting.renderHook(
82
+ () => useRcResource('shared-key', makeSpy, cleanupSpy),
83
+ {
84
+ wrapper,
85
+ },
86
+ )
87
+
88
+ expect(result.current).toBeDefined()
89
+ expect(makeSpy).toHaveBeenCalledTimes(1)
90
+
91
+ // Unmount first consumer; the entity should remain active.
92
+ unmount1()
93
+ expect(cleanupSpy).not.toHaveBeenCalled()
94
+
95
+ // Unmount second consumer; now the entity is disposed.
96
+ unmount2()
97
+ expect(cleanupSpy).toHaveBeenCalledTimes(1)
98
+ })
99
+
100
+ it('should handle rapid key changes correctly', () => {
101
+ const makeSpy = vi.fn(() => Symbol('statefulResource'))
102
+ const cleanupSpy = vi.fn()
103
+
104
+ const { rerender, unmount } = ReactTesting.renderHook(({ key }) => useRcResource(key, makeSpy, cleanupSpy), {
105
+ initialProps: { key: '1' },
106
+ wrapper,
107
+ })
108
+
109
+ // Rapid sequence of key changes.
110
+ rerender({ key: '2' })
111
+ rerender({ key: '3' })
112
+
113
+ // Expect three creations: one each for keys '1', '2', '3'
114
+ expect(makeSpy).toHaveBeenCalledTimes(3)
115
+ // Cleanup should have been triggered for key '1' and key '2'
116
+ expect(cleanupSpy).toHaveBeenCalledTimes(2)
117
+
118
+ unmount()
119
+ // Unmounting the final consumer disposes the key '3' instance.
120
+ expect(cleanupSpy).toHaveBeenCalledTimes(3)
121
+ })
122
+ })
123
+
124
+ // This code was useful to better understand the hook behaviour with and without strict mode
125
+ // describe('debug', () => {
126
+ // const useStrictTest = (key: string) => {
127
+ // const id = React.useId()
128
+ // console.log(key, 'id', id)
129
+
130
+ // const x = React.useMemo(() => {
131
+ // console.log('useMemo', key)
132
+ // return 'hi' + key
133
+ // }, [key])
134
+
135
+ // React.useEffect(() => {
136
+ // console.log('useEffect', key)
137
+ // return () => {
138
+ // console.log('unmount', key)
139
+ // }
140
+ // }, [])
141
+
142
+ // return x
143
+ // }
144
+
145
+ // it('strict mode component', () => {
146
+ // console.log('strict mode component')
147
+ // const Root = () => {
148
+ // useStrictTest('a')
149
+ // return null
150
+ // }
151
+ // const { unmount } = ReactTesting.render(
152
+ // <React.StrictMode>
153
+ // <Root />
154
+ // </React.StrictMode>,
155
+ // )
156
+
157
+ // unmount()
158
+ // })
159
+
160
+ // it('strict mode hook', () => {
161
+ // console.log('strict mode hook')
162
+ // const wrapper: React.FC<{ children: React.ReactNode }> = React.StrictMode
163
+ // const { unmount } = ReactTesting.renderHook(() => useStrictTest('b'), { wrapper })
164
+
165
+ // unmount()
166
+ // })
167
+ // })
@@ -0,0 +1,180 @@
1
+ import * as React from 'react'
2
+
3
+ /**
4
+ * Creates a reference-counted resource object that is "stable" across React lifecycles.
5
+ *
6
+ * The hook is primarily intended for creating stateful objects or entities where:
7
+ * 1) reference identity is crucial (e.g. stateful objects, references, ...)
8
+ * and needed to persist across multiple component instances
9
+ * 2) the `create`/`dispose` functions might be effectful and can be called exactly once per key
10
+ *
11
+ * **Goals:**
12
+ * - Guarantee stable reference identity for stateful entities that are created via the `create` function.
13
+ * - Strong guarantees about the `create`/`dispose` calls (i.e. exactly one `create`/`dispose` call per key)
14
+ * - Ensure that such state is retained across component re-mounts, even in development environments like
15
+ * React Strict Mode or during Fast Refresh.
16
+ * - Automatically handle resource disposal by decrementing a reference count and disposing of the resource
17
+ * when no components are using it.
18
+ *
19
+ * **Behavior:**
20
+ * - On the first render with a specific key, the `create` function is invoked to create the stateful entity,
21
+ * and the resource is stored in a cache with a reference count set to 1.
22
+ * - If another component renders with the same key, the cached entity is reused and its reference count is incremented.
23
+ * - When a component renders with a new key, the previous key's reference count is decremented and, if it reaches zero,
24
+ * the `dispose` function is called for that resource.
25
+ * - Upon component unmount, the reference count is decremented, leading to disposal (via the `dispose` function)
26
+ * if the reference count drops to zero. An unmount is either detected via React's `useEffect` callback or
27
+ * in the useMemo hook when the key changes.
28
+ *
29
+ * Why this is needed in LiveStore:
30
+ * Let's first take a look at the "trivial implementation":
31
+ *
32
+ * ```ts
33
+ * const useSimpleResource = <T>(create: () => T, dispose: (resource: T) => void) => {
34
+ * const val = React.useMemo(() => create(), [create])
35
+ *
36
+ * React.useEffect(() => {
37
+ * return () => {
38
+ * dispose(val)
39
+ * }
40
+ * }, [dispose, val])
41
+
42
+ * return val
43
+ * }
44
+ * ```
45
+ *
46
+ * LiveStore uses this hook to create LiveQuery instances which are stateful and must not be leaked.
47
+ * The simple implementation above would leak the LiveQuery instance if the component is unmounted or props change.
48
+ *
49
+ * **Usage:**
50
+ * ```tsx
51
+ * // Create a stateful object instance for a unique key and share it between components.
52
+ * const statefulObject = useRcResource(
53
+ * 'stable-object-key',
54
+ * () => createObjectInstance(),
55
+ * (object) => object.dispose()
56
+ * );
57
+ * ```
58
+ *
59
+ * **Caveats:**
60
+ * - The `create` function is intentionally omitted from the dependency array in `useMemo` to prevent
61
+ * unintended re-creations of the stateful entity. Avoid closing over changing values within `create`
62
+ * or include them in the `key`.
63
+ * - Ensure that the `dispose` function is stable or properly memoized as its reference is used in a `useEffect`.
64
+ * - Although the caching mechanism prevents duplicate instance creation for the same key, the strategy
65
+ * can interact in unexpected ways with React’s development patterns. Please report any issues if encountered.
66
+ *
67
+ * @template T The type of the stateful entity managed by the hook.
68
+ * @param key A unique identifier for the stateful entity. A change in this key triggers a disposal of the previous resource.
69
+ * @param create Function to create the stateful entity when it does not exist in the cache.
70
+ * @param dispose Function to dispose of the stateful entity when it’s no longer needed. Needs to be stable.
71
+ * @param _options Optional. Additional options such as a debug print callback for logging purposes.
72
+ * @returns The stateful entity corresponding to the provided key.
73
+ */
74
+ export const useRcResource = <T>(
75
+ key: string,
76
+ create: () => T,
77
+ dispose: (resource: NoInfer<T>) => void,
78
+ _options?: { debugPrint?: (resource: NoInfer<T>) => ReadonlyArray<any> },
79
+ ) => {
80
+ const keyRef = React.useRef<string | undefined>(undefined)
81
+ const didDisposeInMemo = React.useRef(false)
82
+
83
+ const resource = React.useMemo(() => {
84
+ // console.debug('useMemo', key)
85
+ if (didDisposeInMemo.current) {
86
+ // console.debug('useMemo', key, 'skip')
87
+ const cachedItem = cache.get(key)
88
+ if (cachedItem !== undefined && cachedItem._tag === 'active') {
89
+ return cachedItem.resource
90
+ }
91
+ }
92
+
93
+ // Check if the key has changed (or is undefined)
94
+ if (keyRef.current !== undefined && keyRef.current !== key) {
95
+ // If the key has changed, decrement the reference on the previous key
96
+ const previousKey = keyRef.current
97
+ const cachedItemForPreviousKey = cache.get(previousKey)
98
+ if (cachedItemForPreviousKey !== undefined && cachedItemForPreviousKey._tag === 'active') {
99
+ // previousKeyRef.current = previousKey
100
+ cachedItemForPreviousKey.rc--
101
+
102
+ // console.debug('useMemo', key, 'rc--', previousKey, cachedItemForPreviousKey.rc)
103
+
104
+ if (cachedItemForPreviousKey.rc === 0) {
105
+ // Clean up the stateful resource if no longer referenced
106
+ dispose(cachedItemForPreviousKey.resource)
107
+ cache.set(previousKey, { _tag: 'destroyed' })
108
+ didDisposeInMemo.current = true
109
+ }
110
+ }
111
+ }
112
+
113
+ const cachedItem = cache.get(key)
114
+ if (cachedItem !== undefined && cachedItem._tag === 'active') {
115
+ // In React Strict Mode, the `useMemo` hook is called multiple times,
116
+ // so we only increment the reference from the first call for this component.
117
+ cachedItem.rc++
118
+ // console.debug('rc++', cachedItem.rc, ...(_options?.debugPrint?.(cachedItem.resource) ?? []))
119
+
120
+ return cachedItem.resource
121
+ }
122
+
123
+ // Create a new stateful resource if not cached
124
+ const resource = create()
125
+ cache.set(key, { _tag: 'active', rc: 1, resource })
126
+ return resource
127
+ // Dependency is deliberately limited to `key` to avoid unintended re-creations.
128
+ // eslint-disable-next-line react-hooks/exhaustive-deps
129
+ }, [key])
130
+
131
+ React.useEffect(() => {
132
+ return () => {
133
+ if (didDisposeInMemo.current) {
134
+ // console.debug('unmount', keyRef.current, 'skip')
135
+ didDisposeInMemo.current = false
136
+ return
137
+ }
138
+
139
+ // console.debug('unmount', keyRef.current)
140
+ const cachedItem = cache.get(key)
141
+ // If the stateful resource is already cleaned up, do nothing.
142
+ if (cachedItem === undefined || cachedItem._tag === 'destroyed') return
143
+
144
+ cachedItem.rc--
145
+
146
+ // console.debug('rc--', cachedItem.rc, ...(_options?.debugPrint?.(cachedItem.resource) ?? []))
147
+
148
+ if (cachedItem.rc === 0) {
149
+ dispose(cachedItem.resource)
150
+ cache.delete(key)
151
+ }
152
+ }
153
+ // We assume the `dispose` function is stable and won't change across renders
154
+ // eslint-disable-next-line react-hooks/exhaustive-deps
155
+ }, [key])
156
+
157
+ keyRef.current = key
158
+
159
+ return resource
160
+ }
161
+
162
+ // NOTE Given `useMemo` will be called multiple times (e.g. when using React Strict mode or Fast Refresh),
163
+ // we are using this cache to avoid starting multiple queries/spans for the same component.
164
+ // This is somewhat against some recommended React best practices, but it should be fine in our case below.
165
+ // Please definitely open an issue if you see or run into any problems with this approach!
166
+ const cache = new Map<
167
+ string,
168
+ | {
169
+ _tag: 'active'
170
+ rc: number
171
+ resource: any
172
+ }
173
+ | {
174
+ _tag: 'destroyed'
175
+ }
176
+ >()
177
+
178
+ export const __resetUseRcResourceCache = () => {
179
+ cache.clear()
180
+ }