ccstate 2.1.0 → 3.0.0
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.
- package/README.md +401 -167
- package/debug/index.cjs +5 -226
- package/debug/index.d.cts +4 -80
- package/debug/index.d.ts +4 -80
- package/debug/index.js +6 -220
- package/index.cjs +5 -349
- package/index.d.cts +3 -103
- package/index.d.ts +3 -103
- package/index.js +6 -336
- package/package.json +1 -13
- package/react/index.cjs +0 -187
- package/react/index.d.cts +0 -67
- package/react/index.d.ts +0 -67
- package/react/index.js +0 -179
package/README.md
CHANGED
|
@@ -10,8 +10,6 @@
|
|
|
10
10
|
[](https://codspeed.io/e7h4n/ccstate)
|
|
11
11
|
[](https://opensource.org/licenses/MIT)
|
|
12
12
|
|
|
13
|
-
English | [中文](README-zh.md)
|
|
14
|
-
|
|
15
13
|
CCState is a semantic, strict, and flexible state management library suitable for medium to large single-page applications with complex state management needs.
|
|
16
14
|
|
|
17
15
|
The name of CCState comes from three basic data types: computed, command, and state.
|
|
@@ -21,7 +19,7 @@ The name of CCState comes from three basic data types: computed, command, and st
|
|
|
21
19
|
- 💯 Simple & Intuitive: Crystal-clear API design with just 3 data types and 2 operations
|
|
22
20
|
- ✅ Rock-solid Reliability: Comprehensive test coverage reaching 100% branch coverage
|
|
23
21
|
- 🪶 Ultra-lightweight: Zero dependencies, only 500 lines of core code
|
|
24
|
-
- 💡 Framework Agnostic: Seamlessly works with React,
|
|
22
|
+
- 💡 Framework Agnostic: Seamlessly works with [React](docs/react.md), [Vue](docs/vue.md), or any UI framework
|
|
25
23
|
- 🚀 Blazing Fast: Optimized performance from day one, 2x-7x faster than Jotai across scenarios
|
|
26
24
|
|
|
27
25
|
## Getting Started
|
|
@@ -64,7 +62,7 @@ Use `useGet` and `useSet` hooks in React to get/set data, and use `useResolved`
|
|
|
64
62
|
|
|
65
63
|
```jsx
|
|
66
64
|
// App.js
|
|
67
|
-
import { useGet, useSet, useResolved } from 'ccstate';
|
|
65
|
+
import { useGet, useSet, useResolved } from 'ccstate-react';
|
|
68
66
|
import { userId$, user$ } from './data';
|
|
69
67
|
|
|
70
68
|
export default function App() {
|
|
@@ -93,8 +91,8 @@ Use `createStore` and `StoreProvider` to provide a CCState store to React, all s
|
|
|
93
91
|
|
|
94
92
|
```tsx
|
|
95
93
|
// main.jsx
|
|
96
|
-
import { createStore
|
|
97
|
-
import {
|
|
94
|
+
import { createStore } from 'ccstate';
|
|
95
|
+
import { StoreProvider } from 'ccstate-react';
|
|
98
96
|
import { createRoot } from 'react-dom/client';
|
|
99
97
|
|
|
100
98
|
import App from './App';
|
|
@@ -104,11 +102,9 @@ const root = createRoot(rootElement);
|
|
|
104
102
|
|
|
105
103
|
const store = createStore();
|
|
106
104
|
root.render(
|
|
107
|
-
<
|
|
108
|
-
<
|
|
109
|
-
|
|
110
|
-
</StoreProvider>
|
|
111
|
-
</StrictMode>,
|
|
105
|
+
<StoreProvider value={store}>
|
|
106
|
+
<App />
|
|
107
|
+
</StoreProvider>,
|
|
112
108
|
);
|
|
113
109
|
```
|
|
114
110
|
|
|
@@ -134,11 +130,14 @@ store.get(userId$); // 0
|
|
|
134
130
|
store.set(userId$, 100);
|
|
135
131
|
store.get(userId$); // 100
|
|
136
132
|
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
133
|
+
const user$ = state<({
|
|
134
|
+
name: 'e7h4n',
|
|
135
|
+
avatar: 'https://avatars.githubusercontent.com/u/813596',
|
|
136
|
+
} | undefined>(undefined);
|
|
137
|
+
store.set({
|
|
138
|
+
name: 'yc-kanyun',
|
|
139
|
+
avatar: 'https://avatars.githubusercontent.com/u/168416598'
|
|
140
140
|
});
|
|
141
|
-
store.get(callback$)(); // console log 'awesome ccstate'
|
|
142
141
|
```
|
|
143
142
|
|
|
144
143
|
These examples should be very easy to understand. You might notice a detail in the examples: all variables returned by `state` have a `$` suffix. This is a naming convention used to distinguish an CCState data type from other regular types. CCState data types must be accessed through the store's get/set methods, and since it's common to convert an CCState data type to a regular type using get, the `$` suffix helps avoid naming conflicts.
|
|
@@ -283,155 +282,11 @@ That's it! Next, you can learn how to use CCState in React.
|
|
|
283
282
|
|
|
284
283
|
## Using in React
|
|
285
284
|
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
```jsx
|
|
289
|
-
// main.tsx
|
|
290
|
-
import { createStore, StoreProvider } from 'ccstate';
|
|
291
|
-
import { App } from './App';
|
|
292
|
-
import { StrictMode } from 'react';
|
|
293
|
-
import { createRoot } from 'react-dom/client';
|
|
294
|
-
|
|
295
|
-
const store = createStore();
|
|
296
|
-
|
|
297
|
-
createRoot(document.getElementById('root')).render(
|
|
298
|
-
<StrictMode>
|
|
299
|
-
<StoreProvider value={store}>
|
|
300
|
-
<App />
|
|
301
|
-
</StoreProvider>
|
|
302
|
-
</StrictMode>,
|
|
303
|
-
);
|
|
304
|
-
```
|
|
305
|
-
|
|
306
|
-
All descendant components within the `StoreProvider` will use the provided store as the caller for `get` and `set` operations.
|
|
307
|
-
|
|
308
|
-
You can place the `StoreProvider` inside or outside of `StrictMode`; the functionality is the same.
|
|
309
|
-
|
|
310
|
-
### Retrieving Values
|
|
311
|
-
|
|
312
|
-
The most basic usage is to use `useGet` to retrieve the value from State or Computed.
|
|
313
|
-
|
|
314
|
-
```jsx
|
|
315
|
-
// data/count.ts
|
|
316
|
-
import { state } from 'ccstate';
|
|
317
|
-
export const count$ = state(0);
|
|
318
|
-
|
|
319
|
-
// App.tsx
|
|
320
|
-
import { useGet } from 'ccstate';
|
|
321
|
-
import { count$ } from './data/count';
|
|
322
|
-
|
|
323
|
-
function App() {
|
|
324
|
-
const count = useGet(count$);
|
|
325
|
-
return <div>{count}</div>;
|
|
326
|
-
}
|
|
327
|
-
```
|
|
328
|
-
|
|
329
|
-
`useGet` returns a `State` or a `Computed` value, and when the value changes, `useGet` triggers a re-render of the component.
|
|
330
|
-
|
|
331
|
-
`useGet` does not do anything special with `Promise` values. In fact, `useGet` is equivalent to a single `store.get` call, plus a `store.sub` to ensure reactive updates to the React component.
|
|
332
|
-
|
|
333
|
-
Two other useful hooks are available when dealing with `Promise` values. First, we introduce `useLoadable`.
|
|
334
|
-
|
|
335
|
-
```jsx
|
|
336
|
-
// data/user.ts
|
|
337
|
-
import { computed } from 'ccstate';
|
|
338
|
-
|
|
339
|
-
export const user$ = computed(async () => {
|
|
340
|
-
return fetch('/api/users/current').then((res) => res.json());
|
|
341
|
-
});
|
|
342
|
-
|
|
343
|
-
// App.tsx
|
|
344
|
-
import { useLoadable } from 'ccstate';
|
|
345
|
-
import { user$ } from './data/user';
|
|
346
|
-
|
|
347
|
-
function App() {
|
|
348
|
-
const user_ = useLoadable(user$);
|
|
349
|
-
if (user_.state === 'loading') return <div>Loading...</div>;
|
|
350
|
-
if (user_.state === 'error') return <div>Error: {user_.error.message}</div>;
|
|
351
|
-
|
|
352
|
-
return <div>{user_.data.name}</div>;
|
|
353
|
-
}
|
|
354
|
-
```
|
|
355
|
-
|
|
356
|
-
`useLoadable` accepts Value/Computed that returns a `Promise` and wraps the result in a `Loadable` structure.
|
|
357
|
-
|
|
358
|
-
```typescript
|
|
359
|
-
type Loadable<T> =
|
|
360
|
-
| {
|
|
361
|
-
state: 'loading';
|
|
362
|
-
}
|
|
363
|
-
| {
|
|
364
|
-
state: 'hasData';
|
|
365
|
-
data: T;
|
|
366
|
-
}
|
|
367
|
-
| {
|
|
368
|
-
state: 'hasError';
|
|
369
|
-
error: unknown;
|
|
370
|
-
};
|
|
371
|
-
```
|
|
372
|
-
|
|
373
|
-
This allows you to render loading and error states in JSX based on the state. `useLoadable` suppresses exceptions, so it will not trigger an `ErrorBoundary`.
|
|
374
|
-
|
|
375
|
-
Another useful hook is `useResolved`, which always returns the resolved value of a `Promise`.
|
|
376
|
-
|
|
377
|
-
```jsx
|
|
378
|
-
// App.tsx
|
|
379
|
-
import { useResolved } from 'ccstate';
|
|
380
|
-
import { user$ } from './data/user';
|
|
381
|
-
|
|
382
|
-
function App() {
|
|
383
|
-
const user = useResolved(user$);
|
|
384
|
-
return <div>{user?.name}</div>;
|
|
385
|
-
}
|
|
386
|
-
```
|
|
387
|
-
|
|
388
|
-
`useResolved` only returns the parameter passed to the resolve function so that it will return `undefined` during loading and when encountering error values. Like `useLoadable`, `useResolved` also suppresses exceptions. In fact, `useResolved` is a simple wrapper around `useLoadable`.
|
|
389
|
-
|
|
390
|
-
```typescript
|
|
391
|
-
// useResolved.ts
|
|
392
|
-
import { useLoadable } from './useLoadable';
|
|
393
|
-
import type { Computed, State } from '../core';
|
|
394
|
-
|
|
395
|
-
export function useResolved<T>(atom: State<Promise<T>> | Computed<Promise<T>>): T | undefined {
|
|
396
|
-
const loadable = useLoadable(atom);
|
|
397
|
-
return loadable.state === 'hasData' ? loadable.data : undefined;
|
|
398
|
-
}
|
|
399
|
-
```
|
|
400
|
-
|
|
401
|
-
### useLastLoadable & useLastResolved
|
|
285
|
+
[Using in React](docs/react.md)
|
|
402
286
|
|
|
403
|
-
|
|
287
|
+
## Using in Vue
|
|
404
288
|
|
|
405
|
-
|
|
406
|
-
import { useLoadable } from 'ccstate';
|
|
407
|
-
import { user$ } from './data/user';
|
|
408
|
-
|
|
409
|
-
function App() {
|
|
410
|
-
const user_ = useLastLoadable(user$); // Keep the previous result during new user$ request, without triggering loading state
|
|
411
|
-
if (user_.state === 'loading') return <div>Loading...</div>;
|
|
412
|
-
if (user_.state === 'error') return <div>Error: {user_.error.message}</div>;
|
|
413
|
-
|
|
414
|
-
return <div>{user_.data.name}</div>;
|
|
415
|
-
}
|
|
416
|
-
```
|
|
417
|
-
|
|
418
|
-
`useLastResolved` behaves similarly - it always returns the last resolved value from a Promise Atom and won't reset to `undefined` when a new Promise is generated.
|
|
419
|
-
|
|
420
|
-
### Updating State / Triggering Command
|
|
421
|
-
|
|
422
|
-
The `useSet` hook can be used to update the value of State, or trigger Command. It returns a function equivalent to `store.set` when called.
|
|
423
|
-
|
|
424
|
-
```jsx
|
|
425
|
-
// App.tsx
|
|
426
|
-
import { useSet } from 'ccstate';
|
|
427
|
-
import { count$ } from './data/count';
|
|
428
|
-
|
|
429
|
-
function App() {
|
|
430
|
-
const setCount = useSet(count$);
|
|
431
|
-
// setCount(x => x + 1) is equivalent to store.set(count$, x => x + 1)
|
|
432
|
-
return <button onClick={() => setCount((x) => x + 1)}>Increment</button>;
|
|
433
|
-
}
|
|
434
|
-
```
|
|
289
|
+
[Using in Vue](docs/vue.md)
|
|
435
290
|
|
|
436
291
|
### Testing & Debugging
|
|
437
292
|
|
|
@@ -457,12 +312,12 @@ Here are some tips to help you better debug during testing.
|
|
|
457
312
|
Use `ConsoleInterceptor` to log most store behaviors to the console during testing:
|
|
458
313
|
|
|
459
314
|
```typescript
|
|
460
|
-
import {
|
|
315
|
+
import { createDebugStore, state, computed, command } from 'ccstate';
|
|
461
316
|
|
|
462
317
|
const base$ = state(1, { debugLabel: 'base$' });
|
|
463
318
|
const derived$ = computed((get) => get(base$) * 2);
|
|
464
319
|
|
|
465
|
-
const store =
|
|
320
|
+
const store = createDebugStore([base$, 'derived'], ['set', 'sub']); // log sub & set actions
|
|
466
321
|
store.set(base$, 1); // console: SET [V0:base$] 1
|
|
467
322
|
store.sub(
|
|
468
323
|
derived$,
|
|
@@ -472,13 +327,17 @@ store.sub(
|
|
|
472
327
|
|
|
473
328
|
## Concept behind CCState
|
|
474
329
|
|
|
475
|
-
CCState is inspired by Jotai.
|
|
330
|
+
CCState is inspired by Jotai. So everyone will ask questions: What's the ability of CCState that Jotai doesn't have?
|
|
331
|
+
|
|
332
|
+
The answer is: CCState intentionally has fewer features, simpler concepts, and less "magic" under the hood.
|
|
333
|
+
|
|
334
|
+
While Jotai is a great state management solution that has benefited the Motiff project significantly, as our project grew larger, especially with the increasing number of states (10k~100k atoms), we felt that some of Jotai's design choices needed adjustments, mainly in these aspects:
|
|
476
335
|
|
|
477
336
|
- Too many combinations of atom init/setter/getter methods, need simplification to reduce team's mental overhead
|
|
478
337
|
- Should reduce reactive capabilities, especially the `onMount` capability - the framework shouldn't provide this ability
|
|
479
338
|
- Some implicit magic operations, especially Promise wrapping, make the application execution process less transparent
|
|
480
339
|
|
|
481
|
-
To address these issues, I created CCState to express my thoughts on state management. Before detailing the differences from Jotai, we need to understand CCState's data types and subscription system.
|
|
340
|
+
To address these issues, I got an idea: "What concepts in Jotai are essential? And which concepts create mental overhead for developers?". Rather than just discussing it theoretically, I decided to try implementing it myself. So I created CCState to express my thoughts on state management. Before detailing the differences from Jotai, we need to understand CCState's data types and subscription system.
|
|
482
341
|
|
|
483
342
|
### More semantic data types
|
|
484
343
|
|
|
@@ -513,7 +372,39 @@ function setupPage() {
|
|
|
513
372
|
|
|
514
373
|
The consideration here is to avoid having callbacks depend on the Store object, which was a key design consideration when creating CCState. In CCState, `sub` is the only API with reactive capabilities, and CCState reduces the complexity of reactive computations by limiting Store usage.
|
|
515
374
|
|
|
516
|
-
|
|
375
|
+
In Jotai, there are no restrictions on writing code that uses sub within a sub callback:
|
|
376
|
+
|
|
377
|
+
```typescript
|
|
378
|
+
store.sub(targetAtom, () => {
|
|
379
|
+
if (store.get(fooAtom)) {
|
|
380
|
+
store.sub(barAtom, () => {
|
|
381
|
+
// ...
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
});
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
In CCState, we can prevent this situation by moving the `Command` definition to a separate file and protecting the Store.
|
|
388
|
+
|
|
389
|
+
```typescript
|
|
390
|
+
// main.ts
|
|
391
|
+
import { callback$ } from './callbacks'
|
|
392
|
+
import { foo$ } from './states
|
|
393
|
+
|
|
394
|
+
function initApp() {
|
|
395
|
+
const store = createStore()
|
|
396
|
+
store.sub(foo$, callback$)
|
|
397
|
+
// do not expose store to outside
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// callbacks.ts
|
|
401
|
+
|
|
402
|
+
export const callback$ = command(({ get, set }) => {
|
|
403
|
+
// there is no way to use store sub
|
|
404
|
+
})
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
Therefore, in CCState, the capability of `sub` is intentionally limited. CCState encourages developers to handle data consistency updates within `Command`, rather than relying on subscription capabilities for reactive data updates. In fact, in a React application, CCState's `sub` is likely only used in conjunction with `useSyncExternalStore` to update views, while in all other scenarios, the code is completely moved into Commands.
|
|
517
408
|
|
|
518
409
|
### Avoid `useEffect` in React
|
|
519
410
|
|
|
@@ -581,6 +472,349 @@ root.render(
|
|
|
581
472
|
);
|
|
582
473
|
```
|
|
583
474
|
|
|
475
|
+
### Less Magic
|
|
476
|
+
|
|
477
|
+
#### No `onMount`: Maintaining Pure State Semantics
|
|
478
|
+
|
|
479
|
+
CCState intentionally omits `onMount` to preserve the side-effect-free nature of `Computed` and `State`. This design choice emphasizes clarity and predictability over convenience.
|
|
480
|
+
|
|
481
|
+
Let's examine a common pattern in Jotai and understand why CCState takes a different approach. [Consider the following scenario](https://codesandbox.io/p/sandbox/gkk43v):
|
|
482
|
+
|
|
483
|
+
```typescript
|
|
484
|
+
// atom.ts
|
|
485
|
+
const countAtom = atom(0);
|
|
486
|
+
countAtom.onMount = (setAtom) => {
|
|
487
|
+
const timer = setInterval(() => {
|
|
488
|
+
setAtom((x) => x + 1);
|
|
489
|
+
}, 1000);
|
|
490
|
+
return () => {
|
|
491
|
+
clearInterval(timer);
|
|
492
|
+
};
|
|
493
|
+
};
|
|
494
|
+
|
|
495
|
+
// App.tsx
|
|
496
|
+
function App() {
|
|
497
|
+
const count = useAtomValue(countAtom)
|
|
498
|
+
return <div>{count}</div>
|
|
499
|
+
}
|
|
500
|
+
```
|
|
501
|
+
|
|
502
|
+
It looks pretty cool, right? Just by using `useAtomValue` in React, you get an auto-incrementing timer. However, this means that subscribing to a `State` can potentially have side effects. Because it has side effects, we need to be very careful handling these side effects in scenarios like `useExternalStore` and `StrictMode`. In CCState, such timer auto-increment operations can only be placed in a `Command`.
|
|
503
|
+
|
|
504
|
+
```tsx
|
|
505
|
+
// logic.ts
|
|
506
|
+
export const count$ = state(0); // state is always effect-less
|
|
507
|
+
|
|
508
|
+
export const setupTimer$ = command(({ set }) => {
|
|
509
|
+
// command is considered to always have side effects
|
|
510
|
+
const timer = setInterval(() => {
|
|
511
|
+
set(count$, (x) => x + 1);
|
|
512
|
+
}, 1000);
|
|
513
|
+
return () => {
|
|
514
|
+
clearInterval(timer);
|
|
515
|
+
};
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
// Must explicitly enable side effects in React
|
|
519
|
+
// App.tsx
|
|
520
|
+
function App() {
|
|
521
|
+
const count = useGet(count$);
|
|
522
|
+
const setupTimer = useSet(setupTimer$);
|
|
523
|
+
|
|
524
|
+
// Rendering App has side effects, so we explicitly enable them
|
|
525
|
+
useEffect(() => {
|
|
526
|
+
return setupTimer();
|
|
527
|
+
}, []);
|
|
528
|
+
|
|
529
|
+
return <div>{count}</div>;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// A more recommended approach is to enable side effects outside of React
|
|
533
|
+
// main.ts
|
|
534
|
+
store.sub(
|
|
535
|
+
// sub is always effect-less to any State
|
|
536
|
+
count$,
|
|
537
|
+
command(() => {
|
|
538
|
+
// ... onCount
|
|
539
|
+
}),
|
|
540
|
+
);
|
|
541
|
+
store.set(setupTimer$); // must setup effect explicitly
|
|
542
|
+
|
|
543
|
+
// ...
|
|
544
|
+
|
|
545
|
+
// The pure effect-less rendering process
|
|
546
|
+
root.render(function App() {
|
|
547
|
+
const count = useGet(count$);
|
|
548
|
+
|
|
549
|
+
return <div>{count}</div>;
|
|
550
|
+
});
|
|
551
|
+
```
|
|
552
|
+
|
|
553
|
+
I'm agree with [explicit is better than implicit](https://peps.python.org/pep-0020/), so CCState removes the `onMount` capability.
|
|
554
|
+
|
|
555
|
+
#### No `loadable` & `unwrap`
|
|
556
|
+
|
|
557
|
+
Jotai provides `loadable` and `unwrap` to handle Promise Atom, to convert them to a flat loading state atom. To implement this functionality, it inevitably needs to use `onMount` to subscribe to Promise changes and then modify its own return value.
|
|
558
|
+
|
|
559
|
+
As mentioned in the previous section, CCState does not provide `onMount`, so `loadable` and `unwrap` are neither present nor necessary in CCState. Instead, React hooks `useLoadable` and `useResolved` are provided as alternatives. The reason for this design is that I noticed a detail - only within a subscription system (like React's rendering part) do we need to convert a Promise into a loading state:
|
|
560
|
+
|
|
561
|
+
```tsx
|
|
562
|
+
// Jotai's example, since try/catch and async/await cannot be used in JSX, loadable is required to flatten the Promise
|
|
563
|
+
const userLoadableAtom = loadable(user$);
|
|
564
|
+
function User() {
|
|
565
|
+
const user = useAtomValue(userLoadableAtom);
|
|
566
|
+
if (user.state === 'loading') return <div>Loading...</div>;
|
|
567
|
+
if (user.state === 'error') return <div>Error: {user.error.message}</div>;
|
|
568
|
+
return <div>{user.data.name}</div>;
|
|
569
|
+
}
|
|
570
|
+
```
|
|
571
|
+
|
|
572
|
+
Or use loadable in the sub callback.
|
|
573
|
+
|
|
574
|
+
```ts
|
|
575
|
+
// Jotai's example
|
|
576
|
+
const userLoadableAtom = loadable(user$);
|
|
577
|
+
|
|
578
|
+
store.sub(userLoadableAtom, () => {
|
|
579
|
+
// Notice how similar this is to the JSX code above
|
|
580
|
+
const user = store.get(userLoadableAtom);
|
|
581
|
+
if (user.state === 'loading') return;
|
|
582
|
+
if (user.state === 'error') return;
|
|
583
|
+
|
|
584
|
+
// ...
|
|
585
|
+
});
|
|
586
|
+
```
|
|
587
|
+
|
|
588
|
+
CCState intentionally avoids overuse of the subscription pattern, encouraging developers to write state changes where they originate rather than where they are responded to.
|
|
589
|
+
|
|
590
|
+
```ts
|
|
591
|
+
// CCState's example, avoid use sub pattern to invoke effect
|
|
592
|
+
const updateUserId$ = command(({ set, get }) => {
|
|
593
|
+
// retrieve userId from somewhere
|
|
594
|
+
set(userId$, USER_ID)
|
|
595
|
+
|
|
596
|
+
set(connectRoom$)
|
|
597
|
+
})
|
|
598
|
+
|
|
599
|
+
const connectRoom$ = command({ set, get }) => {
|
|
600
|
+
const user = await get(user$)
|
|
601
|
+
// ... prepare connection for room
|
|
602
|
+
})
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
In React's subscription-based rendering system, I use `useEffect` to introduce subscription to Promises. The code below shows the actual implementation of `useLoadable`.
|
|
606
|
+
|
|
607
|
+
```ts
|
|
608
|
+
function useLastLoadable<T>(atom: State<Promise<T>> | Computed<Promise<T>>): Loadable<T> {
|
|
609
|
+
const promise = useGet(atom);
|
|
610
|
+
|
|
611
|
+
const [promiseResult, setPromiseResult] = useState<Loadable<T>>({
|
|
612
|
+
state: 'loading',
|
|
613
|
+
});
|
|
614
|
+
|
|
615
|
+
useEffect(() => {
|
|
616
|
+
const ctrl = new AbortController();
|
|
617
|
+
const signal = ctrl.signal;
|
|
618
|
+
|
|
619
|
+
void promise
|
|
620
|
+
.then((ret) => {
|
|
621
|
+
if (signal.aborted) return;
|
|
622
|
+
|
|
623
|
+
setPromiseResult({
|
|
624
|
+
state: 'hasData',
|
|
625
|
+
data: ret,
|
|
626
|
+
});
|
|
627
|
+
})
|
|
628
|
+
.catch((error: unknown) => {
|
|
629
|
+
// ...
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
return () => {
|
|
633
|
+
ctrl.abort();
|
|
634
|
+
};
|
|
635
|
+
}, [promise]);
|
|
636
|
+
|
|
637
|
+
return promiseResult;
|
|
638
|
+
}
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
Finally, CCState only implements Promise flattening in the React-related range, that's enough. By making these design choices, CCState maintains a cleaner separation of concerns, makes side effects more explicit, and reduces the overall complexity of state management. While this might require slightly more explicit code in some cases, it leads to more maintainable and predictable applications.
|
|
642
|
+
|
|
643
|
+
## Technical Details
|
|
644
|
+
|
|
645
|
+
### When Computed Values Are Evaluated
|
|
646
|
+
|
|
647
|
+
The execution of `read` function in `Computed` has several strategies:
|
|
648
|
+
|
|
649
|
+
1. If the `Computed` is not directly or indirectly subscribed, it only be evaluated when accessed by `get`
|
|
650
|
+
1. If the version number of other `Computed` | `State` accessed by the previous `read` is unchanged, use the result of the last `read` without re-evaluating it
|
|
651
|
+
2. Otherwise, re-evaluate `read` and mark its version number +1
|
|
652
|
+
2. Otherwise, if the `Computed` is directly or indirectly subscribed, it will constantly be re-evaluated when its dependency changes
|
|
653
|
+
|
|
654
|
+
I mentioned "directly or indirectly subscribed" twice. Here, we use a simpler term to express it. If a `Computed | Value` is directly or indirectly subscribed, we consider it to be _mounted_. Otherwise, it is deemed to be _unmounted_.
|
|
655
|
+
|
|
656
|
+
Consider this example:
|
|
657
|
+
|
|
658
|
+
```typescript
|
|
659
|
+
const base$ = state(0);
|
|
660
|
+
const branch$ = state('A');
|
|
661
|
+
const derived$ = computed((get) => {
|
|
662
|
+
if (get(branch$) !== 'B') {
|
|
663
|
+
return 0;
|
|
664
|
+
} else {
|
|
665
|
+
return get(base$) * 2;
|
|
666
|
+
}
|
|
667
|
+
});
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
In this example, `derived$` is not directly or indirectly subscribed, so it is always in the _unmounted_ state. At the same time, it has not been read, so it has no dependencies. At this point, resetting `base$` / `branch$` will not trigger the recomputation of `derived$`.
|
|
671
|
+
|
|
672
|
+
```
|
|
673
|
+
store.set(base$, 1) // will not trigger derived$'s read
|
|
674
|
+
store.set(branch$, 'C') // will not trigger derived$'s too
|
|
675
|
+
```
|
|
676
|
+
|
|
677
|
+
Once we read `derived$`, it will automatically record a dependency array.
|
|
678
|
+
|
|
679
|
+
```typescript
|
|
680
|
+
store.get(derived$); // return 0 because of branch$ === 'A'
|
|
681
|
+
```
|
|
682
|
+
|
|
683
|
+
At this point, the dependency array of `derived$` is `[branch$]`, because `derived$` did not access `base$` in the previous execution. Although CCState knows that `derived$` depends on `branch$`, because `branch$` is not mounted, the re-evaluation of `derived$` is lazy.
|
|
684
|
+
|
|
685
|
+
```typescript
|
|
686
|
+
store.set(branch$, 'D'); // will not trigger derived$'s read, until next get(derived$)
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
Once we mount `derived$` by `sub`, all its direct and indirect dependencies will enter the _mounted_ state.
|
|
690
|
+
|
|
691
|
+
```typescript
|
|
692
|
+
store.sub(
|
|
693
|
+
derived$,
|
|
694
|
+
command(() => void 0),
|
|
695
|
+
);
|
|
696
|
+
```
|
|
697
|
+
|
|
698
|
+
The mount graph in CCState is `[derived$, [branch$]]`. When `branch$` is reset, `derived$` will be re-evaluated immediately, and all subscribers will be notified.
|
|
699
|
+
|
|
700
|
+
```typescript
|
|
701
|
+
store.set(branch$, 'B'); // will trigger derived$'s read
|
|
702
|
+
```
|
|
703
|
+
|
|
704
|
+
In this re-evaluation, the dependency array of `derived$` is updated to `[branch$, base$]`, so `base$` will also be _mounted_. Any modification to `base$` will immediately trigger the re-evaluation of `derived$`.
|
|
705
|
+
|
|
706
|
+
```typescript
|
|
707
|
+
store.set(base$, 1); // will trigger derived$'s read and notify all subscribers
|
|
708
|
+
```
|
|
709
|
+
|
|
710
|
+
[Here's an example](https://codesandbox.io/p/sandbox/ds6p44). Open preview in an independent window to check the console output. If you hide the double output and click increment, you will only see the `set` log.
|
|
711
|
+
|
|
712
|
+
```
|
|
713
|
+
[R][SET] V1:count$
|
|
714
|
+
arg: – [function] (1)
|
|
715
|
+
ret: – undefined
|
|
716
|
+
```
|
|
717
|
+
|
|
718
|
+
Click show to make double enter the display state, and you can see the `set` `showDouble$` log and the `double$` evaluation log.
|
|
719
|
+
|
|
720
|
+
```
|
|
721
|
+
[R][SET] V0:showDouble$
|
|
722
|
+
arg: – [function] (1)
|
|
723
|
+
ret: – undefined
|
|
724
|
+
|
|
725
|
+
[R][CPT] C2:doubleCount$
|
|
726
|
+
ret: – 14
|
|
727
|
+
```
|
|
728
|
+
|
|
729
|
+
The abbreviation `CPT` represents `Computed` evaluation, not just a simple read operation. You can also try modifying the parameters of `createDebugStore` in the code to include `get` in the logs, and you'll find that not every `get` triggers a `Computed` evaluation.
|
|
730
|
+
|
|
731
|
+
Click increment to see the `set` trigger the `Computed` evaluation.
|
|
732
|
+
|
|
733
|
+
```
|
|
734
|
+
[R][SET] V1:count$
|
|
735
|
+
arg: – [function] (1)
|
|
736
|
+
[R][CPT] C2:doubleCount$
|
|
737
|
+
ret: – 16
|
|
738
|
+
ret: – undefined
|
|
739
|
+
```
|
|
740
|
+
|
|
741
|
+
### How to Isolate Effect-less Code
|
|
742
|
+
|
|
743
|
+
CCState strives to isolate effect-less code through API capability restrictions and thus introduces two accessor APIs: `get` and `set`. I remember when I first saw Jotai, I raised a question: why can't we directly use the Atom itself to read and write state, just like signals do?
|
|
744
|
+
|
|
745
|
+
Most state libraries allow you to directly read and write state once you get the state object:
|
|
746
|
+
|
|
747
|
+
```typescript
|
|
748
|
+
// Zustand
|
|
749
|
+
const useStore = create((set) => {
|
|
750
|
+
return {
|
|
751
|
+
count: 0,
|
|
752
|
+
updateCount: () => {
|
|
753
|
+
set({
|
|
754
|
+
count: (x) => x + 1,
|
|
755
|
+
});
|
|
756
|
+
},
|
|
757
|
+
};
|
|
758
|
+
});
|
|
759
|
+
useStore.getState().count; // read count is effect-less
|
|
760
|
+
useStore.getState().updateCount(); // update count invoke effect
|
|
761
|
+
|
|
762
|
+
// RxJS
|
|
763
|
+
const count$ = new BehaviorSubject(0);
|
|
764
|
+
count$.value; // read count is effect-less
|
|
765
|
+
count$.next(1); // next count invoke effect
|
|
766
|
+
|
|
767
|
+
// Signals
|
|
768
|
+
const counter = signal(0);
|
|
769
|
+
counter.value; // read value is effect-less
|
|
770
|
+
counter.value = 1; // write value invoke effect
|
|
771
|
+
```
|
|
772
|
+
|
|
773
|
+
So, these libraries cannot isolate effect-less code. Jotai and CCState choose to add a wrapper layer to isolate effect-less code.
|
|
774
|
+
|
|
775
|
+
```typescript
|
|
776
|
+
const count$ = state(0);
|
|
777
|
+
const double$ = computed((get) => {
|
|
778
|
+
get(count$); // read count$ is effect-less
|
|
779
|
+
// In this scope, we can't update any state
|
|
780
|
+
});
|
|
781
|
+
const updateDouble$ = command(({ get, set }) => {
|
|
782
|
+
// This scope can update the state because it has `set` method
|
|
783
|
+
set(count$, get(count$) * 2);
|
|
784
|
+
});
|
|
785
|
+
```
|
|
786
|
+
|
|
787
|
+
Isolating effect-less code is very useful in large projects, but is there a more straightforward way to write it? For example, a straightforward idea is to mark the current state of the `Store` as read-only when entering the `Computed` code block and then restore it to writable when exiting. In read-only mode, all `set` operations are blocked.
|
|
788
|
+
|
|
789
|
+
```typescript
|
|
790
|
+
const counter = state(0);
|
|
791
|
+
const double = computed(() => {
|
|
792
|
+
// set store to read-only
|
|
793
|
+
const result = counter.value * 2; // direct read value from counter instead of get(counter)
|
|
794
|
+
// counter.value = 4; // any write operation in read-only mode will raise an error
|
|
795
|
+
return result;
|
|
796
|
+
}); // exit computed restore store to writable
|
|
797
|
+
|
|
798
|
+
double.value; // will enter read-only mode, evaluate double logic, get the result, and exit read-only mode
|
|
799
|
+
```
|
|
800
|
+
|
|
801
|
+
Unfortunately, this design will fail when encountering asynchronous callback functions in the current JavaScript language capabilities.
|
|
802
|
+
|
|
803
|
+
```typescript
|
|
804
|
+
const double = computed(async () => {
|
|
805
|
+
// set store to read-only
|
|
806
|
+
await delay(TIME_TO_DELAY);
|
|
807
|
+
// How to restore the store to read-only here?
|
|
808
|
+
// ...
|
|
809
|
+
});
|
|
810
|
+
```
|
|
811
|
+
|
|
812
|
+
When encountering `await`, the execution of `double.value` will end, and the framework code in `Computed` can restore the `Store` to writable. If we don't do this, the subsequent set operation will raise an error. But if we do this, when `await` re-enters the `double` read function, it will not be able to restore the `Store` to read-only.
|
|
813
|
+
|
|
814
|
+
Now, we are in the execution context that persists across async tasks; we hope to restore the Store's context to read-only when the async callback re-enters the `read` function. This direction has been proven to have many problems by [zone.js](https://github.com/angular/angular/tree/main/packages/zone.js). This is a dead end.
|
|
815
|
+
|
|
816
|
+
So, I think the only way to implement `Computed`'s effect-less is to separate the atom and the accessor.
|
|
817
|
+
|
|
584
818
|
## Changelog & TODO
|
|
585
819
|
|
|
586
820
|
[Changelog](packages/ccstate/CHANGELOG.md)
|