dev-react-microstore 1.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/.gitattributes +2 -0
- package/LICENSE +21 -0
- package/README.md +183 -0
- package/dist/index.d.mts +21 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +1 -0
- package/package.json +32 -0
- package/src/index.ts +136 -0
- package/tsconfig.json +15 -0
package/.gitattributes
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 OhadBaehr
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# react-microstore
|
|
2
|
+
|
|
3
|
+
A minimal global state manager for React with fine-grained subscriptions.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install react-microstore
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```tsx
|
|
14
|
+
import { createStoreState, useStoreSelector } from 'react-microstore';
|
|
15
|
+
|
|
16
|
+
const counterStore = createStoreState({ count: 0 });
|
|
17
|
+
|
|
18
|
+
function Counter() {
|
|
19
|
+
const { count } = useStoreSelector(counterStore, ['count']);
|
|
20
|
+
|
|
21
|
+
return (
|
|
22
|
+
<div>
|
|
23
|
+
<p>{count}</p>
|
|
24
|
+
<button onClick={() => counterStore.set({ count: count + 1 })}>
|
|
25
|
+
Increment
|
|
26
|
+
</button>
|
|
27
|
+
</div>
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Custom Comparison Function
|
|
33
|
+
|
|
34
|
+
```tsx
|
|
35
|
+
import { createStoreState, useStoreSelector } from 'react-microstore';
|
|
36
|
+
|
|
37
|
+
const taskStore = createStoreState({
|
|
38
|
+
tasks: [
|
|
39
|
+
{ id: 1, title: 'Learn React', completed: false, priority: 'high' },
|
|
40
|
+
{ id: 2, title: 'Build app', completed: false, priority: 'medium' }
|
|
41
|
+
],
|
|
42
|
+
filters: {
|
|
43
|
+
showCompleted: true,
|
|
44
|
+
priorityFilter: null
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
function TaskList() {
|
|
49
|
+
// Only re-render when task completion status changes
|
|
50
|
+
const { tasks } = useStoreSelector(taskStore, [
|
|
51
|
+
{ tasks: (prev, next) =>
|
|
52
|
+
prev.some(t => t.completed) !== next.some(t => t.completed)
|
|
53
|
+
}
|
|
54
|
+
]);
|
|
55
|
+
|
|
56
|
+
const toggleTask = (id) => {
|
|
57
|
+
const currentTasks = taskStore.get().tasks;
|
|
58
|
+
const updatedTasks = currentTasks.map(task =>
|
|
59
|
+
task.id === id ? { ...task, completed: !task.completed } : task
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
taskStore.set({ tasks: updatedTasks });
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
return (
|
|
66
|
+
<ul>
|
|
67
|
+
{tasks.map(task => (
|
|
68
|
+
<li key={task.id}>
|
|
69
|
+
{task.title} - {task.completed ? 'Done' : 'Pending'}
|
|
70
|
+
<button onClick={() => toggleTask(task.id)}>
|
|
71
|
+
Toggle
|
|
72
|
+
</button>
|
|
73
|
+
</li>
|
|
74
|
+
))}
|
|
75
|
+
</ul>
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Example of setting store from outside components
|
|
81
|
+
|
|
82
|
+
```tsx
|
|
83
|
+
import { createStoreState, useStoreSelector } from 'react-microstore';
|
|
84
|
+
|
|
85
|
+
// Create store
|
|
86
|
+
const userStore = createStoreState({
|
|
87
|
+
user: null,
|
|
88
|
+
isLoading: false,
|
|
89
|
+
error: null
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
// Function to update store from anywhere
|
|
93
|
+
export async function fetchUserData(userId) {
|
|
94
|
+
// Update loading state
|
|
95
|
+
userStore.set({ isLoading: true, error: null });
|
|
96
|
+
|
|
97
|
+
try {
|
|
98
|
+
// API call
|
|
99
|
+
const response = await fetch(`/api/users/${userId}`);
|
|
100
|
+
const userData = await response.json();
|
|
101
|
+
|
|
102
|
+
// Update store with fetched data
|
|
103
|
+
userStore.set({
|
|
104
|
+
user: userData,
|
|
105
|
+
isLoading: false
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
return userData;
|
|
109
|
+
} catch (error) {
|
|
110
|
+
// Update store with error
|
|
111
|
+
userStore.set({
|
|
112
|
+
error: error.message,
|
|
113
|
+
isLoading: false
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Components can use the store
|
|
121
|
+
function UserProfile() {
|
|
122
|
+
const { user, isLoading, error } = useStoreSelector(userStore, ['user', 'isLoading', 'error']);
|
|
123
|
+
|
|
124
|
+
if (isLoading) return <div>Loading...</div>;
|
|
125
|
+
if (error) return <div>Error: {error}</div>;
|
|
126
|
+
if (!user) return <div>No user data</div>;
|
|
127
|
+
|
|
128
|
+
return (
|
|
129
|
+
<div>
|
|
130
|
+
<h2>{user.name}</h2>
|
|
131
|
+
<p>Email: {user.email}</p>
|
|
132
|
+
</div>
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Can call the function from anywhere
|
|
137
|
+
// fetchUserData('123');
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## Features
|
|
141
|
+
|
|
142
|
+
- Extremely lightweight (less than 2KB minified)
|
|
143
|
+
- Fine-grained subscriptions to minimize re-renders
|
|
144
|
+
- Custom comparison functions for complex state updates
|
|
145
|
+
- Fully Type-safe
|
|
146
|
+
- No dependencies other than React
|
|
147
|
+
- Update store from anywhere in your application
|
|
148
|
+
|
|
149
|
+
## Development Tools
|
|
150
|
+
|
|
151
|
+
### ESLint Plugin
|
|
152
|
+
|
|
153
|
+
[eslint-plugin-react-microstore](https://www.npmjs.com/package/eslint-plugin-react-microstore) provides ESLint rules to help you write with react-microstore.
|
|
154
|
+
|
|
155
|
+
#### Installation
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
npm install --save-dev eslint-plugin-react-microstore
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
#### Usage
|
|
162
|
+
|
|
163
|
+
ESLint configuration:
|
|
164
|
+
|
|
165
|
+
```json
|
|
166
|
+
{
|
|
167
|
+
"plugins": ["react-microstore"],
|
|
168
|
+
"rules": {
|
|
169
|
+
"react-microstore/no-unused-selector-keys": "warn"
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`react-microstore/no-unused-selector-keys`
|
|
175
|
+
Warns when you select keys in `useStoreSelector` but don't destructure or use them.
|
|
176
|
+
|
|
177
|
+
```tsx
|
|
178
|
+
// ❌ This will trigger the rule
|
|
179
|
+
const { a } = useStoreSelector(store, ['a', 'b']); // 'b' is unused
|
|
180
|
+
|
|
181
|
+
// ✅ This is fine
|
|
182
|
+
const { a, b } = useStoreSelector(store, ['a', 'b']);
|
|
183
|
+
```
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
type StoreListener = () => void;
|
|
2
|
+
declare function createStoreState<T>(initialState: T): {
|
|
3
|
+
get: () => T;
|
|
4
|
+
set: (next: Partial<T>) => void;
|
|
5
|
+
subscribe: (keys: (keyof T)[], listener: StoreListener) => (() => void);
|
|
6
|
+
};
|
|
7
|
+
type StoreType<T> = ReturnType<typeof createStoreState<T>>;
|
|
8
|
+
type PrimitiveKey<T> = keyof T;
|
|
9
|
+
type CompareFn<V> = (prev: V, next: V) => boolean;
|
|
10
|
+
type KeySelector<T> = PrimitiveKey<T>;
|
|
11
|
+
type CustomSelector<T> = {
|
|
12
|
+
[K in keyof T]?: CompareFn<T[K]>;
|
|
13
|
+
};
|
|
14
|
+
type SelectorInput<T> = ReadonlyArray<KeySelector<T> | CustomSelector<T>>;
|
|
15
|
+
type ExtractSelectorKeys<T, S extends SelectorInput<T>> = {
|
|
16
|
+
[K in S[number] extends infer Item ? Item extends keyof T ? Item : keyof Item : never]: T[K];
|
|
17
|
+
};
|
|
18
|
+
type Picked<T, S extends SelectorInput<T>> = ExtractSelectorKeys<T, S>;
|
|
19
|
+
declare function useStoreSelector<T, S extends SelectorInput<T>>(store: StoreType<T>, selector: S): Picked<T, S>;
|
|
20
|
+
|
|
21
|
+
export { createStoreState, useStoreSelector };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
type StoreListener = () => void;
|
|
2
|
+
declare function createStoreState<T>(initialState: T): {
|
|
3
|
+
get: () => T;
|
|
4
|
+
set: (next: Partial<T>) => void;
|
|
5
|
+
subscribe: (keys: (keyof T)[], listener: StoreListener) => (() => void);
|
|
6
|
+
};
|
|
7
|
+
type StoreType<T> = ReturnType<typeof createStoreState<T>>;
|
|
8
|
+
type PrimitiveKey<T> = keyof T;
|
|
9
|
+
type CompareFn<V> = (prev: V, next: V) => boolean;
|
|
10
|
+
type KeySelector<T> = PrimitiveKey<T>;
|
|
11
|
+
type CustomSelector<T> = {
|
|
12
|
+
[K in keyof T]?: CompareFn<T[K]>;
|
|
13
|
+
};
|
|
14
|
+
type SelectorInput<T> = ReadonlyArray<KeySelector<T> | CustomSelector<T>>;
|
|
15
|
+
type ExtractSelectorKeys<T, S extends SelectorInput<T>> = {
|
|
16
|
+
[K in S[number] extends infer Item ? Item extends keyof T ? Item : keyof Item : never]: T[K];
|
|
17
|
+
};
|
|
18
|
+
type Picked<T, S extends SelectorInput<T>> = ExtractSelectorKeys<T, S>;
|
|
19
|
+
declare function useStoreSelector<T, S extends SelectorInput<T>>(store: StoreType<T>, selector: S): Picked<T, S>;
|
|
20
|
+
|
|
21
|
+
export { createStoreState, useStoreSelector };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var l=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames,g=Object.getOwnPropertySymbols;var h=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable;var x=(r,e,t)=>e in r?l(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k=(r,e)=>{for(var t in e||(e={}))h.call(e,t)&&x(r,t,e[t]);if(g)for(var t of g(e))I.call(e,t)&&x(r,t,e[t]);return r};var C=(r,e)=>{for(var t in e)l(r,t,{get:e[t],enumerable:!0})},V=(r,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of v(e))!h.call(r,s)&&s!==t&&l(r,s,{get:()=>e[s],enumerable:!(a=P(e,s))||a.enumerable});return r};var F=r=>V(l({},"__esModule",{value:!0}),r);var R={};C(R,{createStoreState:()=>j,useStoreSelector:()=>O});module.exports=F(R);var f=require("react");function j(r){let e=r,t=new Map;return{get:()=>e,set:T=>{var n;let i=!1,o=[];for(let c in T)Object.is(e[c],T[c])||(i=!0,o.push(c));if(i){e=k(k({},e),T);for(let c of o)(n=t.get(c))==null||n.forEach(b=>b())}},subscribe:(T,i)=>{for(let o of T)t.has(o)||t.set(o,new Set),t.get(o).add(i);return()=>{var o;for(let n of T)(o=t.get(n))==null||o.delete(i)}}}}function O(r,e){let t=(0,f.useRef)(r.get()),a=(0,f.useRef)({}),s=e.flatMap(o=>typeof o=="string"?[{key:o}]:Object.entries(o).map(([n,c])=>({key:n,compare:c}))),m=()=>{let o=r.get(),n=t.current;if(!(!a.current||Object.keys(a.current).length===0||s.some(({key:y,compare:p})=>{let u=n[y],S=o[y];return p?p(u,S):!Object.is(u,S)})))return a.current;t.current=o;let d={};for(let{key:y,compare:p}of s){let u=a.current[y],S=o[y],K=p?p(u,S):!Object.is(u,S);d[y]=K?S:u}return a.current=d,d},T=(()=>{let o=r.get();return s.reduce((n,{key:c})=>(n[c]=o[c],n),{})})();return(0,f.useSyncExternalStore)(o=>r.subscribe(s.map(n=>n.key),o),m,()=>T)}0&&(module.exports={createStoreState,useStoreSelector});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var h=Object.defineProperty;var m=Object.getOwnPropertySymbols;var K=Object.prototype.hasOwnProperty,P=Object.prototype.propertyIsEnumerable;var b=(o,r,t)=>r in o?h(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t,l=(o,r)=>{for(var t in r||(r={}))K.call(r,t)&&b(o,t,r[t]);if(m)for(var t of m(r))P.call(r,t)&&b(o,t,r[t]);return o};import{useRef as g,useSyncExternalStore as v}from"react";function V(o){let r=o,t=new Map;return{get:()=>r,set:c=>{var n;let T=!1,e=[];for(let s in c)Object.is(r[s],c[s])||(T=!0,e.push(s));if(T){r=l(l({},r),c);for(let s of e)(n=t.get(s))==null||n.forEach(k=>k())}},subscribe:(c,T)=>{for(let e of c)t.has(e)||t.set(e,new Set),t.get(e).add(T);return()=>{var e;for(let n of c)(e=t.get(n))==null||e.delete(T)}}}}function F(o,r){let t=g(o.get()),a=g({}),S=r.flatMap(e=>typeof e=="string"?[{key:e}]:Object.entries(e).map(([n,s])=>({key:n,compare:s}))),d=()=>{let e=o.get(),n=t.current;if(!(!a.current||Object.keys(a.current).length===0||S.some(({key:i,compare:p})=>{let y=n[i],u=e[i];return p?p(y,u):!Object.is(y,u)})))return a.current;t.current=e;let f={};for(let{key:i,compare:p}of S){let y=a.current[i],u=e[i],x=p?p(y,u):!Object.is(y,u);f[i]=x?u:y}return a.current=f,f},c=(()=>{let e=o.get();return S.reduce((n,{key:s})=>(n[s]=e[s],n),{})})();return v(e=>o.subscribe(S.map(n=>n.key),e),d,()=>c)}export{V as createStoreState,F as useStoreSelector};
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "dev-react-microstore",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A minimal global state manager for React with fine-grained subscriptions.",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"build": "tsup src/index.ts --format esm,cjs --dts --minify",
|
|
9
|
+
"prepare": "npm run build"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"react",
|
|
13
|
+
"state",
|
|
14
|
+
"store",
|
|
15
|
+
"microstore",
|
|
16
|
+
"selector",
|
|
17
|
+
"hook",
|
|
18
|
+
"tiny",
|
|
19
|
+
"minimal"
|
|
20
|
+
],
|
|
21
|
+
"author": "Ohad Baehr",
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"react": ">=17.0.0",
|
|
25
|
+
"react-dom": ">=17.0.0"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/react": "^19.1.2",
|
|
29
|
+
"tsup": "^8.4.0",
|
|
30
|
+
"typescript": "^5.8.3"
|
|
31
|
+
}
|
|
32
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { useRef, useSyncExternalStore } from 'react';
|
|
2
|
+
type StoreListener = () => void;
|
|
3
|
+
|
|
4
|
+
export function createStoreState<T>(initialState: T) {
|
|
5
|
+
let state = initialState;
|
|
6
|
+
|
|
7
|
+
// Map from key to set of subscribers interested in that key
|
|
8
|
+
const keyListeners = new Map<keyof T, Set<StoreListener>>();
|
|
9
|
+
|
|
10
|
+
const get = () => state;
|
|
11
|
+
|
|
12
|
+
const set = (next: Partial<T>) => {
|
|
13
|
+
let changed = false;
|
|
14
|
+
const updatedKeys: (keyof T)[] = [];
|
|
15
|
+
|
|
16
|
+
for (const key in next) {
|
|
17
|
+
if (!Object.is(state[key], next[key])) {
|
|
18
|
+
changed = true;
|
|
19
|
+
updatedKeys.push(key);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (!changed) return;
|
|
24
|
+
|
|
25
|
+
state = { ...state, ...next };
|
|
26
|
+
|
|
27
|
+
for (const key of updatedKeys) {
|
|
28
|
+
keyListeners.get(key)?.forEach(listener => listener());
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const subscribe = (keys: (keyof T)[], listener: StoreListener): (() => void) => {
|
|
33
|
+
for (const key of keys) {
|
|
34
|
+
if (!keyListeners.has(key)) {
|
|
35
|
+
keyListeners.set(key, new Set());
|
|
36
|
+
}
|
|
37
|
+
keyListeners.get(key)!.add(listener);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return () => {
|
|
41
|
+
for (const key of keys) {
|
|
42
|
+
keyListeners.get(key)?.delete(listener);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
return { get, set, subscribe };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type StoreType<T> = ReturnType<typeof createStoreState<T>>;
|
|
51
|
+
type PrimitiveKey<T> = keyof T;
|
|
52
|
+
type CompareFn<V> = (prev: V, next: V) => boolean;
|
|
53
|
+
|
|
54
|
+
type KeySelector<T> = PrimitiveKey<T>;
|
|
55
|
+
type CustomSelector<T> = { [K in keyof T]?: CompareFn<T[K]> };
|
|
56
|
+
type SelectorInput<T> = ReadonlyArray<KeySelector<T> | CustomSelector<T>>;
|
|
57
|
+
|
|
58
|
+
type ExtractSelectorKeys<T, S extends SelectorInput<T>> = {
|
|
59
|
+
[K in S[number] extends infer Item
|
|
60
|
+
? Item extends keyof T
|
|
61
|
+
? Item
|
|
62
|
+
: keyof Item
|
|
63
|
+
: never]: T[K];
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
type Picked<T, S extends SelectorInput<T>> = ExtractSelectorKeys<T, S>;
|
|
67
|
+
|
|
68
|
+
type NormalizedSelector<T> = {
|
|
69
|
+
key: keyof T;
|
|
70
|
+
compare?: CompareFn<T[keyof T]>;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
export function useStoreSelector<T, S extends SelectorInput<T>>(
|
|
74
|
+
store: StoreType<T>,
|
|
75
|
+
selector: S
|
|
76
|
+
): Picked<T, S> {
|
|
77
|
+
const lastState = useRef(store.get());
|
|
78
|
+
const lastSelected = useRef<Partial<T>>({});
|
|
79
|
+
|
|
80
|
+
const normalized = selector.flatMap((item): NormalizedSelector<T>[] => {
|
|
81
|
+
if (typeof item === 'string') {
|
|
82
|
+
return [{ key: item as keyof T }];
|
|
83
|
+
}
|
|
84
|
+
return Object.entries(item).map(([key, compare]) => ({
|
|
85
|
+
key: key as keyof T,
|
|
86
|
+
compare: compare as CompareFn<T[keyof T]>,
|
|
87
|
+
}));
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const getSnapshot = () => {
|
|
91
|
+
const current = store.get();
|
|
92
|
+
const prev = lastState.current;
|
|
93
|
+
|
|
94
|
+
const isFirstRun = !lastSelected.current || Object.keys(lastSelected.current).length === 0;
|
|
95
|
+
|
|
96
|
+
const changed = isFirstRun || normalized.some(({ key, compare }) => {
|
|
97
|
+
const prevVal = prev[key];
|
|
98
|
+
const nextVal = current[key];
|
|
99
|
+
return compare ? compare(prevVal, nextVal) : !Object.is(prevVal, nextVal);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
if (!changed) {
|
|
103
|
+
return lastSelected.current as Picked<T, S>;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
lastState.current = current;
|
|
107
|
+
|
|
108
|
+
const nextSelected: Partial<T> = {};
|
|
109
|
+
|
|
110
|
+
for (const { key, compare } of normalized) {
|
|
111
|
+
const prevVal = lastSelected.current[key];
|
|
112
|
+
const nextVal = current[key];
|
|
113
|
+
const hasChanged = compare
|
|
114
|
+
? compare(prevVal as T[keyof T], nextVal as T[keyof T])
|
|
115
|
+
: !Object.is(prevVal, nextVal);
|
|
116
|
+
|
|
117
|
+
nextSelected[key] = hasChanged ? nextVal : prevVal;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
lastSelected.current = nextSelected;
|
|
121
|
+
|
|
122
|
+
return nextSelected as Picked<T, S>;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const staticSnapshot = (() => {
|
|
126
|
+
const current = store.get();
|
|
127
|
+
return normalized.reduce((acc, { key }) => {
|
|
128
|
+
acc[key] = current[key];
|
|
129
|
+
return acc;
|
|
130
|
+
}, {} as Partial<T>) as Picked<T, S>;
|
|
131
|
+
})();
|
|
132
|
+
|
|
133
|
+
const subscribe = (onStoreChange: () => void) =>
|
|
134
|
+
store.subscribe(normalized.map(sel => sel.key), onStoreChange);
|
|
135
|
+
return useSyncExternalStore(subscribe, getSnapshot, () => staticSnapshot);
|
|
136
|
+
}
|
package/tsconfig.json
ADDED