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

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 (76) 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.d.ts +5 -2
  7. package/dist/LiveStoreProvider.d.ts.map +1 -1
  8. package/dist/LiveStoreProvider.js +2 -17
  9. package/dist/LiveStoreProvider.js.map +1 -1
  10. package/dist/__tests__/fixture.d.ts +6 -8
  11. package/dist/__tests__/fixture.d.ts.map +1 -1
  12. package/dist/__tests__/fixture.js +6 -7
  13. package/dist/__tests__/fixture.js.map +1 -1
  14. package/dist/experimental/components/LiveList.d.ts +2 -2
  15. package/dist/experimental/components/LiveList.d.ts.map +1 -1
  16. package/dist/experimental/components/LiveList.js +5 -4
  17. package/dist/experimental/components/LiveList.js.map +1 -1
  18. package/dist/mod.d.ts +0 -1
  19. package/dist/mod.d.ts.map +1 -1
  20. package/dist/mod.js +0 -1
  21. package/dist/mod.js.map +1 -1
  22. package/dist/useAtom.d.ts +4 -2
  23. package/dist/useAtom.d.ts.map +1 -1
  24. package/dist/useAtom.js +32 -28
  25. package/dist/useAtom.js.map +1 -1
  26. package/dist/useQuery.d.ts +26 -3
  27. package/dist/useQuery.d.ts.map +1 -1
  28. package/dist/useQuery.js +60 -45
  29. package/dist/useQuery.js.map +1 -1
  30. package/dist/useQuery.test.js +70 -16
  31. package/dist/useQuery.test.js.map +1 -1
  32. package/dist/useRcRef.d.ts +72 -0
  33. package/dist/useRcRef.d.ts.map +1 -0
  34. package/dist/useRcRef.js +146 -0
  35. package/dist/useRcRef.js.map +1 -0
  36. package/dist/useRcRef.test.d.ts +2 -0
  37. package/dist/useRcRef.test.d.ts.map +1 -0
  38. package/dist/useRcRef.test.js +128 -0
  39. package/dist/useRcRef.test.js.map +1 -0
  40. package/dist/useRcResource.d.ts +76 -0
  41. package/dist/useRcResource.d.ts.map +1 -0
  42. package/dist/useRcResource.js +150 -0
  43. package/dist/useRcResource.js.map +1 -0
  44. package/dist/useRcResource.test.d.ts +2 -0
  45. package/dist/useRcResource.test.d.ts.map +1 -0
  46. package/dist/useRcResource.test.js +122 -0
  47. package/dist/useRcResource.test.js.map +1 -0
  48. package/dist/useRow.d.ts +10 -7
  49. package/dist/useRow.d.ts.map +1 -1
  50. package/dist/useRow.js +23 -22
  51. package/dist/useRow.js.map +1 -1
  52. package/dist/useRow.test.js +62 -80
  53. package/dist/useRow.test.js.map +1 -1
  54. package/dist/useScopedQuery.d.ts +10 -4
  55. package/dist/useScopedQuery.d.ts.map +1 -1
  56. package/dist/useScopedQuery.js +96 -52
  57. package/dist/useScopedQuery.js.map +1 -1
  58. package/dist/useScopedQuery.test.js +13 -12
  59. package/dist/useScopedQuery.test.js.map +1 -1
  60. package/package.json +6 -6
  61. package/src/LiveStoreContext.ts +10 -6
  62. package/src/LiveStoreProvider.tsx +3 -19
  63. package/src/__snapshots__/useQuery.test.tsx.snap +2011 -0
  64. package/src/__snapshots__/useRow.test.tsx.snap +335 -142
  65. package/src/__tests__/fixture.tsx +6 -9
  66. package/src/experimental/components/LiveList.tsx +8 -7
  67. package/src/mod.ts +0 -1
  68. package/src/useAtom.ts +22 -11
  69. package/src/useQuery.test.tsx +165 -67
  70. package/src/useQuery.ts +84 -54
  71. package/src/useRcResource.test.tsx +167 -0
  72. package/src/useRcResource.ts +180 -0
  73. package/src/useRow.test.tsx +73 -107
  74. package/src/useRow.ts +42 -40
  75. package/src/useScopedQuery.test.tsx +0 -96
  76. package/src/useScopedQuery.ts +0 -143
package/dist/useQuery.js CHANGED
@@ -3,26 +3,26 @@ import { deepEqual, indent } from '@livestore/utils';
3
3
  import * as otel from '@opentelemetry/api';
4
4
  import React from 'react';
5
5
  import { useStore } from './LiveStoreContext.js';
6
+ import { useRcResource } from './useRcResource.js';
6
7
  import { originalStackLimit } from './utils/stack-info.js';
7
8
  import { useStateRefWithReactiveInput } from './utils/useStateRefWithReactiveInput.js';
8
9
  /**
9
- * NOTE Some folks have suggested to use `React.useSyncExternalStore`, however, it's not doing anything special
10
- * for what's needed here, so we handle everything manually.
10
+ * Returns the result of a query and subscribes to future updates.
11
+ *
12
+ * Example:
13
+ * ```tsx
14
+ * const App = () => {
15
+ * const todos = useQuery(queryDb(tables.todos.query.where({ complete: true })))
16
+ * return <div>{todos.map((todo) => <div key={todo.id}>{todo.title}</div>)}</div>
17
+ * }
18
+ * ```
11
19
  */
20
+ export const useQuery = (queryDef, options) => useQueryRef(queryDef, options).valueRef.current;
12
21
  /**
13
- * This is needed because the `React.useMemo` call below, can sometimes be called multiple times 🤷,
14
- * so we need to "cache" the fact that we've already started a span for this component.
15
- * The map entry is being removed again in the `React.useEffect` call below.
16
22
  */
17
- const spanAlreadyStartedCache = new Map();
18
- export const useQuery = (query) => useQueryRef(query).current;
19
- /**
20
- *
21
- */
22
- export const useQueryRef = (query$, parentOtelContext) => {
23
- const { store } = useStore();
24
- React.useDebugValue(`LiveStore:useQuery:${query$.id}:${query$.label}`);
25
- // console.debug(`LiveStore:useQuery:${query$.id}:${query$.label}`)
23
+ export const useQueryRef = (queryDef, options) => {
24
+ const { store } = useStore({ store: options?.store });
25
+ const rcRefKey = `${store.storeId}_${queryDef.hash}`;
26
26
  const stackInfo = React.useMemo(() => {
27
27
  Error.stackTraceLimit = 10;
28
28
  // eslint-disable-next-line unicorn/error-message
@@ -30,23 +30,29 @@ export const useQueryRef = (query$, parentOtelContext) => {
30
30
  Error.stackTraceLimit = originalStackLimit;
31
31
  return extractStackInfoFromStackTrace(stack);
32
32
  }, []);
33
- // The following `React.useMemo` and `React.useEffect` calls are used to start and end a span for the lifetime of this component.
34
- const { span, otelContext } = React.useMemo(() => {
35
- const existingSpan = spanAlreadyStartedCache.get(query$);
36
- if (existingSpan !== undefined)
37
- return existingSpan;
38
- const span = store.otel.tracer.startSpan(`LiveStore:useQuery:${query$.label}`, { attributes: { label: query$.label, stackInfo: JSON.stringify(stackInfo) } }, parentOtelContext ?? store.otel.queriesSpanContext);
33
+ const { queryRcRef, span, otelContext } = useRcResource(rcRefKey, () => {
34
+ const queryDefLabel = queryDef.label;
35
+ const span = store.otel.tracer.startSpan(options?.otelSpanName ?? `LiveStore:useQuery:${queryDefLabel}`, { attributes: { label: queryDefLabel, firstStackInfo: JSON.stringify(stackInfo) } }, options?.otelContext ?? store.otel.queriesSpanContext);
39
36
  const otelContext = otel.trace.setSpan(otel.context.active(), span);
40
- spanAlreadyStartedCache.set(query$, { span, otelContext });
41
- return { span, otelContext };
42
- }, [parentOtelContext, query$, stackInfo, store.otel.queriesSpanContext, store.otel.tracer]);
37
+ const queryRcRef = queryDef.make(store.reactivityGraph.context, otelContext);
38
+ return { queryRcRef, span, otelContext };
39
+ },
40
+ // We need to keep the queryRcRef alive a bit longer, so we have a second `useRcResource` below
41
+ // which takes care of disposing the queryRcRef
42
+ () => { });
43
+ const query$ = queryRcRef.value;
44
+ React.useDebugValue(`LiveStore:useQuery:${query$.id}:${query$.label}`);
45
+ // console.debug(`LiveStore:useQuery:${query$.id}:${query$.label}`)
43
46
  const initialResult = React.useMemo(() => {
44
47
  try {
45
- return query$.run(otelContext, {
46
- _tag: 'react',
47
- api: 'useQuery',
48
- label: query$.label,
49
- stackInfo,
48
+ return query$.run({
49
+ otelContext,
50
+ debugRefreshReason: {
51
+ _tag: 'react',
52
+ api: 'useQuery',
53
+ label: `useQuery:initial-run:${query$.label}`,
54
+ stackInfo,
55
+ },
50
56
  });
51
57
  }
52
58
  catch (cause) {
@@ -65,27 +71,36 @@ Stack trace:
65
71
  }, [otelContext, query$, stackInfo]);
66
72
  // We know the query has a result by the time we use it; so we can synchronously populate a default state
67
73
  const [valueRef, setValue] = useStateRefWithReactiveInput(initialResult);
68
- React.useEffect(() => () => {
69
- spanAlreadyStartedCache.delete(query$);
70
- span.end();
71
- }, [query$, span]);
74
+ // TODO we probably need to change the order of `useEffect` calls, so we destroy the query at the end
75
+ // before calling the LS `onEffect` on it
72
76
  // Subscribe to future updates for this query
73
77
  React.useEffect(() => {
78
+ // TODO double check whether we still need `activeSubscriptions`
74
79
  query$.activeSubscriptions.add(stackInfo);
75
80
  // Dynamic queries only set their actual label after they've been run the first time,
76
81
  // so we're also updating the span name here.
77
- span.updateName(`LiveStore:useQuery:${query$.label}`);
78
- return store.subscribe(query$, (newValue) => {
79
- // NOTE: we return a reference to the result object within LiveStore;
80
- // this implies that app code must not mutate the results, or else
81
- // there may be weird reactivity bugs.
82
- if (deepEqual(newValue, valueRef.current) === false) {
83
- setValue(newValue);
84
- }
85
- }, () => {
86
- query$.activeSubscriptions.delete(stackInfo);
87
- }, { label: query$.label, otelContext });
88
- }, [stackInfo, query$, setValue, store, valueRef, otelContext, span]);
89
- return valueRef;
82
+ span.updateName(options?.otelSpanName ?? `LiveStore:useQuery:${query$.label}`);
83
+ return store.subscribe(query$, {
84
+ onUpdate: (newValue) => {
85
+ // NOTE: we return a reference to the result object within LiveStore;
86
+ // this implies that app code must not mutate the results, or else
87
+ // there may be weird reactivity bugs.
88
+ if (deepEqual(newValue, valueRef.current) === false) {
89
+ setValue(newValue);
90
+ }
91
+ },
92
+ onUnsubsubscribe: () => {
93
+ query$.activeSubscriptions.delete(stackInfo);
94
+ },
95
+ label: query$.label,
96
+ otelContext,
97
+ });
98
+ }, [stackInfo, query$, setValue, store, valueRef, otelContext, span, options?.otelSpanName]);
99
+ useRcResource(rcRefKey, () => ({ queryRcRef, span }), ({ queryRcRef, span }) => {
100
+ // console.debug('deref', queryRcRef.value.id, queryRcRef.value.label)
101
+ queryRcRef.deref();
102
+ span.end();
103
+ });
104
+ return { valueRef, queryRcRef };
90
105
  };
91
106
  //# sourceMappingURL=useQuery.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useQuery.js","sourceRoot":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ACD,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,WAAW;SACZ,CAAC,CAAA;IACJ,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAA;IAE5F,aAAa,CACX,QAAQ,EACR,GAAG,EAAE,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,EAC5B,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,EAAE;QACvB,sEAAsE;QACtE,UAAU,CAAC,KAAK,EAAE,CAAA;QAClB,IAAI,CAAC,GAAG,EAAE,CAAA;IACZ,CAAC,CACF,CAAA;IAED,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAA;AACjC,CAAC,CAAA"}
@@ -1,45 +1,99 @@
1
- import { queryDb } from '@livestore/livestore';
1
+ import { makeRef, queryDb } from '@livestore/livestore';
2
+ import * as LiveStore from '@livestore/livestore';
3
+ import { RG } from '@livestore/livestore/internal/testing-utils';
2
4
  import { Effect, Schema } from '@livestore/utils/effect';
3
- import { renderHook } from '@testing-library/react';
5
+ import { Vitest } from '@livestore/utils/node-vitest';
6
+ import * as ReactTesting from '@testing-library/react';
4
7
  import React from 'react';
5
- import { describe, expect, it } from 'vitest';
8
+ // @ts-expect-error no types
9
+ import * as ReactWindow from 'react-window';
10
+ import { expect } from 'vitest';
6
11
  import { makeTodoMvcReact, tables, todos } from './__tests__/fixture.js';
7
12
  import * as LiveStoreReact from './mod.js';
8
- describe('useQuery', () => {
9
- it('simple', () => Effect.gen(function* () {
10
- const { wrapper, store, makeRenderCount } = yield* makeTodoMvcReact();
11
- const renderCount = makeRenderCount();
13
+ import { __resetUseRcResourceCache } from './useRcResource.js';
14
+ Vitest.describe.each([{ strictMode: true }, { strictMode: false }])('useQuery (strictMode=%s)', ({ strictMode }) => {
15
+ Vitest.afterEach(() => {
16
+ RG.__resetIds();
17
+ __resetUseRcResourceCache();
18
+ });
19
+ Vitest.scopedLive('simple', () => Effect.gen(function* () {
20
+ const { wrapper, store, renderCount } = yield* makeTodoMvcReact({ strictMode });
12
21
  const allTodos$ = queryDb({ query: `select * from todos`, schema: Schema.Array(tables.todos.schema) });
13
- const { result } = renderHook(() => {
22
+ const { result } = ReactTesting.renderHook(() => {
14
23
  renderCount.inc();
15
24
  return LiveStoreReact.useQuery(allTodos$);
16
25
  }, { wrapper });
17
26
  expect(result.current.length).toBe(0);
18
27
  expect(renderCount.val).toBe(1);
19
- React.act(() => store.mutate(todos.insert({ id: 't1', text: 'buy milk', completed: false })));
28
+ expect(store.reactivityGraph.getSnapshot({ includeResults: true })).toMatchSnapshot();
29
+ console.log('before mutation');
30
+ ReactTesting.act(() => store.mutate(todos.insert({ id: 't1', text: 'buy milk', completed: false })));
31
+ console.log('after mutation');
20
32
  expect(result.current.length).toBe(1);
21
33
  expect(result.current[0].text).toBe('buy milk');
22
34
  expect(renderCount.val).toBe(2);
23
- }).pipe(Effect.scoped, Effect.tapCauseLogPretty, Effect.runPromise));
24
- it('same `useQuery` hook invoked with different queries', () => Effect.gen(function* () {
25
- const { wrapper, store, makeRenderCount } = yield* makeTodoMvcReact();
26
- const renderCount = makeRenderCount();
35
+ expect(store.reactivityGraph.getSnapshot({ includeResults: true })).toMatchSnapshot();
36
+ }));
37
+ Vitest.scopedLive('same `useQuery` hook invoked with different queries', () => Effect.gen(function* () {
38
+ const { wrapper, store, renderCount } = yield* makeTodoMvcReact({ strictMode });
27
39
  const todo1$ = queryDb({ query: `select * from todos where id = 't1'`, schema: Schema.Array(tables.todos.schema) }, { label: 'libraryTracksView1' });
28
40
  const todo2$ = queryDb({ query: `select * from todos where id = 't2'`, schema: Schema.Array(tables.todos.schema) }, { label: 'libraryTracksView2' });
29
41
  store.mutate(todos.insert({ id: 't1', text: 'buy milk', completed: false }), todos.insert({ id: 't2', text: 'buy eggs', completed: false }));
30
- const { result, rerender } = renderHook((todoId) => {
42
+ const { result, rerender } = ReactTesting.renderHook((todoId) => {
31
43
  renderCount.inc();
32
44
  const query$ = React.useMemo(() => (todoId === 't1' ? todo1$ : todo2$), [todoId]);
33
45
  return LiveStoreReact.useQuery(query$)[0].text;
34
46
  }, { wrapper, initialProps: 't1' });
35
47
  expect(result.current).toBe('buy milk');
36
48
  expect(renderCount.val).toBe(1);
37
- React.act(() => store.mutate(todos.update({ where: { id: 't1' }, values: { text: 'buy soy milk' } })));
49
+ expect(store.reactivityGraph.getSnapshot({ includeResults: true })).toMatchSnapshot('1: after first render');
50
+ ReactTesting.act(() => store.mutate(todos.update({ where: { id: 't1' }, values: { text: 'buy soy milk' } })));
38
51
  expect(result.current).toBe('buy soy milk');
39
52
  expect(renderCount.val).toBe(2);
53
+ expect(store.reactivityGraph.getSnapshot({ includeResults: true })).toMatchSnapshot('2: after first mutation');
40
54
  rerender('t2');
41
55
  expect(result.current).toBe('buy eggs');
42
56
  expect(renderCount.val).toBe(3);
43
- }).pipe(Effect.scoped, Effect.tapCauseLogPretty, Effect.runPromise));
57
+ expect(store.reactivityGraph.getSnapshot({ includeResults: true })).toMatchSnapshot('3: after forced rerender');
58
+ }));
59
+ Vitest.scopedLive('filtered dependency query', () => Effect.gen(function* () {
60
+ const { wrapper, store, renderCount } = yield* makeTodoMvcReact({ strictMode });
61
+ const filter$ = makeRef('t1', { label: 'id-filter' });
62
+ const todo$ = queryDb((get) => tables.todos.query.where('id', get(filter$)), { label: 'todo' });
63
+ store.mutate(todos.insert({ id: 't1', text: 'buy milk', completed: false }), todos.insert({ id: 't2', text: 'buy eggs', completed: false }));
64
+ const { result } = ReactTesting.renderHook(() => {
65
+ renderCount.inc();
66
+ return LiveStoreReact.useQuery(todo$)[0].text;
67
+ }, { wrapper });
68
+ expect(result.current).toBe('buy milk');
69
+ expect(renderCount.val).toBe(1);
70
+ expect(store.reactivityGraph.getSnapshot({ includeResults: true })).toMatchSnapshot();
71
+ ReactTesting.act(() => store.mutate(todos.update({ where: { id: 't1' }, values: { text: 'buy soy milk' } })));
72
+ expect(result.current).toBe('buy soy milk');
73
+ expect(renderCount.val).toBe(2);
74
+ expect(store.reactivityGraph.getSnapshot({ includeResults: true })).toMatchSnapshot();
75
+ ReactTesting.act(() => store.setRef(filter$, 't2'));
76
+ expect(result.current).toBe('buy eggs');
77
+ expect(renderCount.val).toBe(3);
78
+ expect(store.reactivityGraph.getSnapshot({ includeResults: true })).toMatchSnapshot();
79
+ }));
80
+ // NOTE this test covers some special react lifecyle paths which I couldn't easily reproduce without react-window
81
+ // it basically causes a "query swap" in the `useMemo` and both a `useEffect` cleanup call.
82
+ // To handle this properly we introduced the `_tag: 'destroyed'` state in the `spanAlreadyStartedCache`.
83
+ Vitest.scopedLive('should work for a list with react-window', () => Effect.gen(function* () {
84
+ const { wrapper } = yield* makeTodoMvcReact({ strictMode });
85
+ const ListWrapper = ({ numItems }) => {
86
+ return (React.createElement(ReactWindow.FixedSizeList, { height: 100, width: 100, itemSize: 10, itemCount: numItems, itemData: Array.from({ length: numItems }, (_, i) => i).reverse() }, ListItem));
87
+ };
88
+ const ListItem = ({ data: ids, index }) => {
89
+ const id = ids[index];
90
+ const res = LiveStoreReact.useQuery(LiveStore.computed(() => id, { label: `ListItem.${id}`, deps: id }));
91
+ return React.createElement("div", { role: "listitem" }, res);
92
+ };
93
+ const renderResult = ReactTesting.render(React.createElement(ListWrapper, { numItems: 1 }), { wrapper });
94
+ expect(renderResult.container.textContent).toBe('0');
95
+ renderResult.rerender(React.createElement(ListWrapper, { numItems: 2 }));
96
+ expect(renderResult.container.textContent).toBe('10');
97
+ }));
44
98
  });
45
99
  //# sourceMappingURL=useQuery.test.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useQuery.test.js","sourceRoot":"","sources":["../src/useQuery.test.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAA;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,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,UAAU,IAAE,GAAG,CAAO,CAAA;QACzC,CAAC,CAAA;QAED,MAAM,YAAY,GAAG,YAAY,CAAC,MAAM,CAAC,oBAAC,WAAW,IAAC,QAAQ,EAAE,CAAC,GAAI,EAAE,EAAE,OAAO,EAAE,CAAC,CAAA;QAEnF,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QAEpD,YAAY,CAAC,QAAQ,CAAC,oBAAC,WAAW,IAAC,QAAQ,EAAE,CAAC,GAAI,CAAC,CAAA;QAEnD,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACvD,CAAC,CAAC,CACH,CAAA;AACH,CAAC,CACF,CAAA"}
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Creates a reference-counted ref that is "stable" across React lifecycles.
3
+ *
4
+ * The hook is primarily intended for creating stateful objects or entities where
5
+ * reference identity is crucial (e.g. stateful objects, references, ...)
6
+ * needed to persist across multiple component instances. Instead of focusing on the cost of execution,
7
+ * its main goal is to ensure that the same instance is reused while there is at least one consumer,
8
+ * and properly disposed of only when no longer referenced.
9
+ *
10
+ * **Goals:**
11
+ * - Guarantee stable reference identity for stateful entities that are created via the `make` function.
12
+ * - Ensure that such state persists across component re-mounts, even in development environments like
13
+ * React Strict Mode or during Fast Refresh.
14
+ * - Automatically handle resource disposal by decrementing a reference count and disposing of the resource
15
+ * when no components are using it.
16
+ *
17
+ * **Behavior:**
18
+ * - On the first render with a specific key, the `make` function is invoked to create the stateful entity,
19
+ * and the resource is stored in a cache with a reference count set to 1.
20
+ * - If another component renders with the same key, the cached entity is reused and its reference count is incremented.
21
+ * - When a component renders with a new key, the previous key's reference count is decremented and, if it reaches zero,
22
+ * the `dispose` function is called for that resource.
23
+ * - Upon component unmount, the reference count is decremented, leading to disposal (via the `dispose` function)
24
+ * if the reference count drops to zero. An unmount is either detected via React's `useEffect` callback or
25
+ * in the useMemo hook when the key changes.
26
+ *
27
+ * Why this is needed in LiveStore:
28
+ * - Let's first take a look at the "trivial implementation":
29
+ * ```ts
30
+ * const useSimpleResource = <T>(make: () => T, dispose: (resource: T) => void) => {
31
+ * const val = React.useMemo(() => make(), [make])
32
+ *
33
+ * React.useEffect(() => {
34
+ * return () => {
35
+ * dispose(val)
36
+ * }
37
+ * }, [dispose, val])
38
+
39
+ * return val
40
+ * }
41
+ * ```
42
+ *
43
+ * **Usage:**
44
+ * ```tsx
45
+ * // Create a stateful object instance for a unique key and share it between components.
46
+ * const statefulObject = useRcResource(
47
+ * 'stable-object-key',
48
+ * () => createObjectInstance(),
49
+ * (object) => object.dispose()
50
+ * );
51
+ * ```
52
+ *
53
+ * **Caveats:**
54
+ * - The `make` function is intentionally omitted from the dependency array in `useMemo` to prevent
55
+ * unintended re-creations of the stateful entity. Avoid closing over changing values within `make`
56
+ * or include them in the `key`.
57
+ * - Ensure that the `dispose` function is stable or properly memoized as its reference is used in a `useEffect`.
58
+ * - Although the caching mechanism prevents duplicate instance creation for the same key, the strategy
59
+ * can interact in unexpected ways with React’s development patterns. Please report any issues if encountered.
60
+ *
61
+ * @template T The type of the stateful entity managed by the hook.
62
+ * @param key A unique identifier for the stateful entity. A change in this key triggers a disposal of the previous resource.
63
+ * @param make Function to create the stateful entity when it does not exist in the cache.
64
+ * @param dispose Function to dispose of the stateful entity when it’s no longer needed. Needs to be stable.
65
+ * @param _options Optional. Additional options such as a debug print callback for logging purposes.
66
+ * @returns The stateful entity corresponding to the provided key.
67
+ */
68
+ export declare const useRcResource: <T>(key: string, make: () => T, dispose: (resource: NoInfer<T>) => void, _options?: {
69
+ debugPrint?: (resource: NoInfer<T>) => ReadonlyArray<any>;
70
+ }) => any;
71
+ export declare const __resetUseRcRefCache: () => void;
72
+ //# sourceMappingURL=useRcRef.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRcRef.d.ts","sourceRoot":"","sources":["../src/useRcRef.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkEG;AACH,eAAO,MAAM,aAAa,GAAI,CAAC,OACxB,MAAM,QACL,MAAM,CAAC,WACJ,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,IAAI,aAC5B;IAAE,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,aAAa,CAAC,GAAG,CAAC,CAAA;CAAE,QAkFzE,CAAA;AAkBD,eAAO,MAAM,oBAAoB,YAEhC,CAAA"}
@@ -0,0 +1,146 @@
1
+ import * as React from 'react';
2
+ /**
3
+ * Creates a reference-counted ref that is "stable" across React lifecycles.
4
+ *
5
+ * The hook is primarily intended for creating stateful objects or entities where
6
+ * reference identity is crucial (e.g. stateful objects, references, ...)
7
+ * needed to persist across multiple component instances. Instead of focusing on the cost of execution,
8
+ * its main goal is to ensure that the same instance is reused while there is at least one consumer,
9
+ * and properly disposed of only when no longer referenced.
10
+ *
11
+ * **Goals:**
12
+ * - Guarantee stable reference identity for stateful entities that are created via the `make` function.
13
+ * - Ensure that such state persists across component re-mounts, even in development environments like
14
+ * React Strict Mode or during Fast Refresh.
15
+ * - Automatically handle resource disposal by decrementing a reference count and disposing of the resource
16
+ * when no components are using it.
17
+ *
18
+ * **Behavior:**
19
+ * - On the first render with a specific key, the `make` function is invoked to create the stateful entity,
20
+ * and the resource is stored in a cache with a reference count set to 1.
21
+ * - If another component renders with the same key, the cached entity is reused and its reference count is incremented.
22
+ * - When a component renders with a new key, the previous key's reference count is decremented and, if it reaches zero,
23
+ * the `dispose` function is called for that resource.
24
+ * - Upon component unmount, the reference count is decremented, leading to disposal (via the `dispose` function)
25
+ * if the reference count drops to zero. An unmount is either detected via React's `useEffect` callback or
26
+ * in the useMemo hook when the key changes.
27
+ *
28
+ * Why this is needed in LiveStore:
29
+ * - Let's first take a look at the "trivial implementation":
30
+ * ```ts
31
+ * const useSimpleResource = <T>(make: () => T, dispose: (resource: T) => void) => {
32
+ * const val = React.useMemo(() => make(), [make])
33
+ *
34
+ * React.useEffect(() => {
35
+ * return () => {
36
+ * dispose(val)
37
+ * }
38
+ * }, [dispose, val])
39
+
40
+ * return val
41
+ * }
42
+ * ```
43
+ *
44
+ * **Usage:**
45
+ * ```tsx
46
+ * // Create a stateful object instance for a unique key and share it between components.
47
+ * const statefulObject = useRcResource(
48
+ * 'stable-object-key',
49
+ * () => createObjectInstance(),
50
+ * (object) => object.dispose()
51
+ * );
52
+ * ```
53
+ *
54
+ * **Caveats:**
55
+ * - The `make` function is intentionally omitted from the dependency array in `useMemo` to prevent
56
+ * unintended re-creations of the stateful entity. Avoid closing over changing values within `make`
57
+ * or include them in the `key`.
58
+ * - Ensure that the `dispose` function is stable or properly memoized as its reference is used in a `useEffect`.
59
+ * - Although the caching mechanism prevents duplicate instance creation for the same key, the strategy
60
+ * can interact in unexpected ways with React’s development patterns. Please report any issues if encountered.
61
+ *
62
+ * @template T The type of the stateful entity managed by the hook.
63
+ * @param key A unique identifier for the stateful entity. A change in this key triggers a disposal of the previous resource.
64
+ * @param make Function to create the stateful entity when it does not exist in the cache.
65
+ * @param dispose Function to dispose of the stateful entity when it’s no longer needed. Needs to be stable.
66
+ * @param _options Optional. Additional options such as a debug print callback for logging purposes.
67
+ * @returns The stateful entity corresponding to the provided key.
68
+ */
69
+ export const useRcResource = (key, make, dispose, _options) => {
70
+ const keyRef = React.useRef(undefined);
71
+ const didDisposeInMemo = React.useRef(false);
72
+ const resource = React.useMemo(() => {
73
+ // console.debug('useMemo', key)
74
+ if (didDisposeInMemo.current) {
75
+ // console.debug('useMemo', key, 'skip')
76
+ const cachedItem = cache.get(key);
77
+ if (cachedItem !== undefined && cachedItem._tag === 'active') {
78
+ return cachedItem.resource;
79
+ }
80
+ }
81
+ // Check if the key has changed (or is undefined)
82
+ if (keyRef.current !== undefined && keyRef.current !== key) {
83
+ // If the key has changed, decrement the reference on the previous key
84
+ const previousKey = keyRef.current;
85
+ const cachedItemForPreviousKey = cache.get(previousKey);
86
+ if (cachedItemForPreviousKey !== undefined && cachedItemForPreviousKey._tag === 'active') {
87
+ // previousKeyRef.current = previousKey
88
+ cachedItemForPreviousKey.rc--;
89
+ // console.debug('useMemo', key, 'rc--', previousKey, cachedItemForPreviousKey.rc)
90
+ if (cachedItemForPreviousKey.rc === 0) {
91
+ // Clean up the stateful resource if no longer referenced
92
+ dispose(cachedItemForPreviousKey.resource);
93
+ cache.set(previousKey, { _tag: 'destroyed' });
94
+ didDisposeInMemo.current = true;
95
+ }
96
+ }
97
+ }
98
+ const cachedItem = cache.get(key);
99
+ if (cachedItem !== undefined && cachedItem._tag === 'active') {
100
+ // In React Strict Mode, the `useMemo` hook is called multiple times,
101
+ // so we only increment the reference from the first call for this component.
102
+ cachedItem.rc++;
103
+ // console.debug('rc++', cachedItem.rc, ...(_options?.debugPrint?.(cachedItem.resource) ?? []))
104
+ return cachedItem.resource;
105
+ }
106
+ // Create a new stateful resource if not cached
107
+ const resource = make();
108
+ cache.set(key, { _tag: 'active', rc: 1, resource });
109
+ return resource;
110
+ // Dependency is deliberately limited to `key` to avoid unintended re-creations.
111
+ // eslint-disable-next-line react-hooks/exhaustive-deps
112
+ }, [key]);
113
+ React.useEffect(() => {
114
+ return () => {
115
+ if (didDisposeInMemo.current) {
116
+ // console.debug('unmount', keyRef.current, 'skip')
117
+ didDisposeInMemo.current = false;
118
+ return;
119
+ }
120
+ // console.debug('unmount', keyRef.current)
121
+ const cachedItem = cache.get(key);
122
+ // If the stateful resource is already cleaned up, do nothing.
123
+ if (cachedItem === undefined || cachedItem._tag === 'destroyed')
124
+ return;
125
+ cachedItem.rc--;
126
+ // console.debug('rc--', cachedItem.rc, ...(_options?.debugPrint?.(cachedItem.resource) ?? []))
127
+ if (cachedItem.rc === 0) {
128
+ dispose(cachedItem.resource);
129
+ cache.delete(key);
130
+ }
131
+ };
132
+ // We assume the `dispose` function is stable and won't change across renders
133
+ // eslint-disable-next-line react-hooks/exhaustive-deps
134
+ }, [key]);
135
+ keyRef.current = key;
136
+ return resource;
137
+ };
138
+ // NOTE Given `useMemo` will be called multiple times (e.g. when using React Strict mode or Fast Refresh),
139
+ // we are using this cache to avoid starting multiple queries/spans for the same component.
140
+ // This is somewhat against some recommended React best practices, but it should be fine in our case below.
141
+ // Please definitely open an issue if you see or run into any problems with this approach!
142
+ const cache = new Map();
143
+ export const __resetUseRcRefCache = () => {
144
+ cache.clear();
145
+ };
146
+ //# sourceMappingURL=useRcRef.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRcRef.js","sourceRoot":"","sources":["../src/useRcRef.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,GAAW,EACX,IAAa,EACb,OAAuC,EACvC,QAAwE,EACxE,EAAE;IACF,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAqB,SAAS,CAAC,CAAA;IAC1D,MAAM,gBAAgB,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IAE5C,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE;QAClC,gCAAgC;QAChC,IAAI,gBAAgB,CAAC,OAAO,EAAE,CAAC;YAC7B,wCAAwC;YACxC,MAAM,UAAU,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;YACjC,IAAI,UAAU,KAAK,SAAS,IAAI,UAAU,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC7D,OAAO,UAAU,CAAC,QAAQ,CAAA;YAC5B,CAAC;QACH,CAAC;QAED,iDAAiD;QACjD,IAAI,MAAM,CAAC,OAAO,KAAK,SAAS,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