react-shared-states 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/.editorconfig ADDED
@@ -0,0 +1,9 @@
1
+ # EditorConfig is awesome: https://editorconfig.org
2
+
3
+ root = true
4
+
5
+ [*]
6
+ indent_size = 4
7
+
8
+ [*.md]
9
+ indent_size = 2
@@ -0,0 +1,128 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, religion, or sexual identity
10
+ and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the
26
+ overall community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or
31
+ advances of any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email
35
+ address, without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ hichem.taboukouyout@hichemtab-tech.me.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series
86
+ of actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or
93
+ permanent ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within
113
+ the community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.0, available at
119
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120
+
121
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
+ enforcement ladder](https://github.com/mozilla/diversity).
123
+
124
+ [homepage]: https://www.contributor-covenant.org
125
+
126
+ For answers to common questions about this code of conduct, see the FAQ at
127
+ https://www.contributor-covenant.org/faq. Translations are available at
128
+ https://www.contributor-covenant.org/translations.
@@ -0,0 +1,112 @@
1
+ # 👥 Contributing to React shared states
2
+
3
+ Thank you for your interest in contributing to this project! Open source contributions help improve projects, introduce new ideas, and build a better community.
4
+
5
+ ---
6
+
7
+ ## 🚨 Before You Start
8
+
9
+ Before contributing, please:
10
+
11
+ - Browse [existing issues](https://github.com/HichemTab-tech/react-shared-states/issues) to see if your issue or feature idea has already been raised.
12
+ - If your idea or issue hasn't been addressed, feel free to [create a new issue](https://github.com/HichemTab-tech/react-shared-states/issues/new).
13
+
14
+ ---
15
+
16
+ ## 📄 Code of Conduct
17
+
18
+ Please ensure your contributions follow these general guidelines:
19
+
20
+ - Be respectful and professional at all times.
21
+ - Treat everyone in the community with kindness.
22
+ - Discuss constructively and respectfully.
23
+
24
+ Any harassment or inappropriate behavior is strictly prohibited.
25
+
26
+ ---
27
+
28
+ ## ⚙️ Setting Up Your Environment
29
+
30
+ To start contributing to the project, follow these steps:
31
+
32
+ 1. Fork this repository on GitHub.
33
+ 2. Clone your forked repository:
34
+
35
+ ```sh
36
+ git clone https://github.com/YOUR_GITHUB_USERNAME/react-shared-states
37
+ cd react-shared-states
38
+ ```
39
+
40
+ 3. Install dependencies with your preferred package manager:
41
+
42
+ - npm:
43
+ ```sh
44
+ npm install
45
+ ```
46
+
47
+ - pnpm:
48
+ ```sh
49
+ pnpm install
50
+ ```
51
+
52
+ ---
53
+
54
+ ## 🔨 Making Changes
55
+
56
+ To submit a feature or bug fix, please:
57
+
58
+ 1. Create a branch from the `main` branch. Name the branch according to your feature or bug fix:
59
+
60
+ ```sh
61
+ git checkout -b feature/CoolNewFeature
62
+ ```
63
+
64
+ or for bug fixes:
65
+
66
+ ```sh
67
+ git checkout -b fix/bug-description
68
+ ```
69
+
70
+ 2. After making your necessary changes, run relevant checks and tests to ensure everything works correctly:
71
+
72
+ ```sh
73
+ npm test
74
+ ```
75
+
76
+ or with pnpm:
77
+
78
+ ```sh
79
+ pnpm test
80
+ ```
81
+
82
+ 3. Stage and commit your changes clearly describing what has been changed:
83
+
84
+ ```sh
85
+ git add .
86
+ git commit -m 'feat: Add CoolNewFeature to improve performance'
87
+ ```
88
+
89
+ 4. Push your branch to your forked repo:
90
+
91
+ ```sh
92
+ git push origin feature/CoolNewFeature
93
+ ```
94
+
95
+ ---
96
+
97
+ ## 📝 Submitting a Pull Request
98
+
99
+ When your changes are ready:
100
+
101
+ 1. Open GitHub and navigate to your forked repository.
102
+ 2. Click `Compare & pull request`.
103
+ 3. Clearly explain the following in your pull request description:
104
+ - **What changes you made and why they are needed.**
105
+ - **Any linked relevant issues (e.g., "**Closes #number**").**
106
+ 4. Wait for project maintainers review to suggest changes or to merge your PR.
107
+
108
+ ---
109
+
110
+ ## 📌 Commit Message Guidelines
111
+
112
+ Write clear commit messages, formatted this way:
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Hichem Taboukouyout
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,359 @@
1
+
2
+ # React Shared States
3
+
4
+ **_Global state made as simple as useState, with zero config, built-in async caching, and automatic scoping._**
5
+
6
+ ![react-shared-states banner](assets/banner.png)
7
+
8
+ ---
9
+
10
+ [![npm version](https://img.shields.io/npm/v/react-shared-states)](https://www.npmjs.com/package/react-shared-states)
11
+ [![bundle size](https://img.shields.io/bundlephobia/minzip/react-shared-states)](https://bundlephobia.com/package/react-shared-states)
12
+ [![license](https://img.shields.io/github/license/HichemTab-tech/react-shared-states)](LICENSE)
13
+
14
+
15
+ Tiny, ergonomic, convention‑over‑configuration state & async function sharing for React. Global by default, trivially scoped when you need isolation, and opt‑in static APIs when you must touch state outside components. As simple as `useState`, as flexible as Zustand, without boilerplate like Redux.
16
+
17
+ ## 🔥 Why this instead of Redux / Zustand / Context soup?
18
+ * 0 config. Just pick a key: `useSharedState('cart', [])`.
19
+ * Automatic scoping: nearest `SharedStatesProvider` wins; omit it for global.
20
+ * Cross‑tree sharing via named scopes (two providers with same `scopeName` share data) – powerful for portals/modals/micro‑frontends.
21
+ * Async functions become cached shared resources via `useSharedFunction` (built‑in loading, error, results, reentrancy guard, manual or forced refresh).
22
+ * Static APIs (`sharedStatesApi`, `sharedFunctionsApi`) let you prime / read / mutate outside React (SSR, event buses, dev tools, tests).
23
+ * No custom store objects, reducers, actions, selectors, immer, proxies, or serialization hoops.
24
+ * Predictable: key + scope ⇒ value. That’s it.
25
+
26
+
27
+ ## 🚀 Install
28
+
29
+ ```sh
30
+ npm install react-shared-states
31
+ ```
32
+ or
33
+ ```sh
34
+ pnpm add react-shared-states
35
+ ```
36
+
37
+ ## ☕ 60‑Second TL;DR
38
+ ```tsx
39
+ import { useSharedState } from 'react-shared-states';
40
+
41
+ function A(){
42
+ const [count, setCount] = useSharedState('counter', 0);
43
+ return <button onClick={()=>setCount(c=>c+1)}>A {count}</button>;
44
+ }
45
+ function B(){
46
+ const [count] = useSharedState('counter', 0);
47
+ return <span>B sees {count}</span>;
48
+ }
49
+
50
+ function App() {
51
+
52
+ return (
53
+ <>
54
+ <A/>
55
+ <B/>
56
+ </>
57
+ )
58
+ }
59
+ ```
60
+ Same key ⇒ same state (global scope by default).
61
+
62
+ Add a scope:
63
+ ```tsx
64
+ import { SharedStatesProvider, useSharedState } from 'react-shared-states';
65
+
66
+ function Scoped(){
67
+ const [count, set] = useSharedState('counter', 0); // isolated inside provider
68
+ return <button onClick={()=>set(c=>c+1)}>Scoped {count}</button>;
69
+ }
70
+
71
+ function App() {
72
+
73
+ return (
74
+ <>
75
+ <A/>
76
+ <B/>
77
+ <SharedStatesProvider>
78
+ <Scoped/>
79
+ </SharedStatesProvider>
80
+ </>
81
+ )
82
+ }
83
+ ```
84
+
85
+ Override / jump to a named scope explicitly:
86
+ ```tsx
87
+ useSharedState('counter', 0, 'modal'); // 3rd arg is scopeName override
88
+ ```
89
+
90
+ Two separate trees with the same `SharedStatesProvider scopeName` share their data:
91
+ ```tsx
92
+ <SharedStatesProvider scopeName="modal">
93
+ <ModalContent/>
94
+ </SharedStatesProvider>
95
+ <Portal target={...}>
96
+ <SharedStatesProvider scopeName="modal">
97
+ <FloatingToolbar/>
98
+ </SharedStatesProvider>
99
+ </Portal>
100
+ function App() {
101
+
102
+ return (
103
+ <>
104
+ <SharedStatesProvider scopeName="modal">
105
+ <ModalContent/>
106
+ </SharedStatesProvider>
107
+ <Portal target={...}>
108
+ <SharedStatesProvider scopeName="modal">
109
+ <FloatingToolbar/>
110
+ </SharedStatesProvider>
111
+ </Portal>
112
+ </>
113
+ )
114
+ }
115
+ ```
116
+
117
+ Async shared function (one fetch, instant reuse when new component mounts):
118
+ ```tsx
119
+ import { useEffect, useState } from 'react';
120
+ import { useSharedFunction } from 'react-shared-states';
121
+
122
+ // Any async callback you want to share
123
+ const fetchCurrentUser = () => fetch('/api/me').then(r => r.json());
124
+
125
+ function UserHeader(){
126
+ const { state, trigger } = useSharedFunction('current-user', fetchCurrentUser);
127
+
128
+ useEffect(() => {
129
+
130
+ trigger();
131
+
132
+ }, []);
133
+
134
+ if(state.isLoading && !state.results) return <p>Loading user...</p>;
135
+
136
+ if(state.error) return <p style={{color:'red'}}>Failed.</p>;
137
+
138
+ return <h1>{state.results.name}</h1>;
139
+ }
140
+
141
+ function UserDetails(){
142
+ const { state, trigger } = useSharedFunction('current-user', fetchCurrentUser);
143
+ // This effect will run when the component appears later, but fetch is already cached so trigger does nothing.
144
+ useEffect(() => {
145
+
146
+ trigger();
147
+
148
+ }, []);
149
+
150
+ if(state.isLoading && !state.results) return <p>Loading user...</p>; // this will not happen, cuz we already have the shared result
151
+ if(state.error) return <p style={{color:'red'}}>Failed.</p>; // this will not happen, cuz we already have the shared result
152
+
153
+ return <pre>{JSON.stringify(state.results, null, 2)}</pre>;
154
+ }
155
+
156
+ export default function App(){
157
+ const [showDetails, setShowDetails] = useState(false);
158
+ return (
159
+ <div>
160
+ <UserHeader/>
161
+ <button onClick={()=>setShowDetails(s=>!s)}>
162
+ {showDetails ? 'Hide details' : 'Show details'}
163
+ </button>
164
+ {showDetails && <UserDetails/>}
165
+ </div>
166
+ );
167
+ }
168
+
169
+ // If you need to force a refetch somewhere:
170
+ // const { forceTrigger } = useSharedFunction('current-user', fetchCurrentUser);
171
+ // forceTrigger(); // bypass cache & re-run
172
+ ```
173
+
174
+
175
+ ## 🧠 Core Concepts
176
+ | Concept | Summary |
177
+ |-------------------|---------------------------------------------------------------------------------------------------------------------------------|
178
+ | Global by default | No provider necessary. Same key => shared state. |
179
+ | Scoping | Wrap with `SharedStatesProvider` to isolate. Nearest provider wins. |
180
+ | Named scopes | `scopeName` prop lets distant providers sync (same name ⇒ same bucket). Unnamed providers auto‑generate a random isolated name. |
181
+ | Manual override | Third param in `useSharedState` / `useSharedFunction` enforces a specific scope ignoring tree search. |
182
+ | Shared functions | Encapsulate async logic: single flight + cached result + `error` + `isLoading` + opt‑in refresh. |
183
+ | Static APIs | Access state/functions outside components (`sharedStatesApi`, `sharedFunctionsApi`). |
184
+
185
+
186
+ ## 🏗️ Sharing State (`useSharedState`)
187
+ Signature: `const [value, setValue] = useSharedState(key, initialValue, scopeName?);`
188
+
189
+ Behavior:
190
+ * First hook call (per key + scope) seeds with `initialValue`.
191
+ * Subsequent mounts with same key+scope ignore their `initialValue` (consistent source of truth).
192
+ * Setter accepts either value or updater `(prev)=>next`.
193
+ * React batching + equality check: listeners fire only when the value reference actually changes.
194
+
195
+ ### Examples
196
+ 1. Global theme
197
+ ```tsx
198
+ const [theme, setTheme] = useSharedState('theme', 'light');
199
+ ```
200
+ 2. Isolated wizard progress
201
+ ```tsx
202
+ <SharedStatesProvider>
203
+ <Wizard/>
204
+ </SharedStatesProvider>
205
+ ```
206
+ 3. Forcing cross‑portal sync
207
+ ```tsx
208
+ <SharedStatesProvider scopeName="nav" children={<PrimaryNav/>} />
209
+ <Portal>
210
+ <SharedStatesProvider scopeName="nav" children={<MobileNav/>} />
211
+ </Portal>
212
+ ```
213
+ 4. Overriding nearest provider
214
+ ```tsx
215
+ // Even if inside a provider, this explicitly binds to global
216
+ const [flag, setFlag] = useSharedState('feature-x-enabled', false, '_global');
217
+ ```
218
+
219
+
220
+ ## ⚡ Shared Async Functions (`useSharedFunction`)
221
+ Signature:
222
+ ```ts
223
+ const { state, trigger, forceTrigger, clear } = useSharedFunction(key, asyncFn, scopeName?);
224
+ ```
225
+ `state` shape: `{ results?: T; isLoading: boolean; error?: unknown }`
226
+
227
+ Semantics:
228
+ * First `trigger()` (implicit or manual) runs the function; subsequent calls do nothing while loading or after success (cached) unless you `forceTrigger()`.
229
+ * Multiple components with the same key+scope share one execution + result.
230
+ * `clear()` deletes the cache (next trigger re-runs).
231
+ * You decide when to invoke `trigger` (e.g. on mount, on button click, when dependencies change, etc.).
232
+
233
+ ### Pattern: lazy load on first render
234
+ ```tsx
235
+ function Profile({id}:{id:string}){
236
+ const { state, trigger } = useSharedFunction(`profile-${id}`, () => fetch(`/api/p/${id}`).then(r=>r.json()));
237
+
238
+ if(!state.results && !state.isLoading) trigger();
239
+ if(state.isLoading) return <p>Loading...</p>;
240
+ return <pre>{JSON.stringify(state.results,null,2)}</pre>
241
+ }
242
+ ```
243
+
244
+ ### Pattern: always fetch fresh
245
+ ```tsx
246
+ const { state, forceTrigger } = useSharedFunction('server-time', () => fetch('/time').then(r=>r.text()));
247
+ const refresh = () => forceTrigger();
248
+ ```
249
+
250
+
251
+ ## 🛰️ Static APIs (outside React)
252
+ Useful for SSR hydration, event listeners, debugging, imperative workflows.
253
+
254
+ ```ts
255
+ import { sharedStatesApi, sharedFunctionsApi } from 'react-shared-states';
256
+
257
+ // Preload
258
+ sharedStatesApi.set('bootstrap-data', { user: {...} });
259
+
260
+ // Read later
261
+ const user = sharedStatesApi.get('bootstrap-data');
262
+
263
+ // Inspect all
264
+ console.log(sharedStatesApi.getAll()); // Map with prefixed keys
265
+
266
+ // For shared functions
267
+ const fnState = sharedFunctionsApi.get('profile-123');
268
+ ```
269
+
270
+ ## API summary:
271
+
272
+ | API | Methods |
273
+ |----------------------|--------------------------------------------------------------------------------------|
274
+ | `sharedStatesApi` | `get(key, scope?)`, `set(key,val,scope?)`, `has`, `clear`, `clearAll`, `getAll()` |
275
+ | `sharedFunctionsApi` | `get(key, scope?)` (returns fn state), `set`, `has`, `clear`, `clearAll`, `getAll()` |
276
+
277
+ `scope` defaults to `"_global"`. Internally keys are stored as `${scope}_${key}`.
278
+
279
+
280
+ ## 🧩 Scoping Rules Deep Dive
281
+ Resolution order used inside hooks:
282
+ 1. Explicit 3rd parameter (`scopeName`)
283
+ 2. Nearest `SharedStatesProvider` above the component
284
+ 3. The implicit global scope (`_global`)
285
+
286
+ Unnamed providers auto‑generate a random scope name: each mount = isolated island.
287
+
288
+ Two providers sharing the same `scopeName` act as a single logical scope even if they are disjoint in the tree (great for portals / microfrontends).
289
+
290
+
291
+ ## 🆚 Comparison Snapshot
292
+ | Criterion | react-shared-states | Redux Toolkit | Zustand |
293
+ |----------------|------------------------------------------|----------------------|----------------------------------|
294
+ | Setup | Install & call hook | Slice + store config | Create store function |
295
+ | Global state | Yes (by key) | Yes | Yes |
296
+ | Scoped state | Built-in (providers + names + overrides) | Needs custom logic | Needs multiple stores / contexts |
297
+ | Async helper | `useSharedFunction` (cache + status) | Thunks / RTK Query | Manual or middleware |
298
+ | Boilerplate | Near zero | Moderate | Low |
299
+ | Static access | Yes (APIs) | Yes (store) | Yes (store) |
300
+ | Learning curve | Minutes | Higher | Low |
301
+
302
+
303
+ ## 🧪 Testing Tips
304
+ * Use static APIs to assert state after component interactions.
305
+ * `sharedStatesApi.clearAll()` in `afterEach` to isolate tests.
306
+ * For async functions: trigger once, await UI stabilization, assert `results` present.
307
+
308
+
309
+ ## ❓ FAQ
310
+ **Q: How do I reset a single shared state?**
311
+ `sharedStatesApi.clear('key')` or inside component: call a setter with the initial value.
312
+
313
+ **Q: Can I pre-hydrate data on the server?**
314
+ Yes. Call `sharedStatesApi.set(...)` during bootstrap, then first client hook usage will pick it up.
315
+
316
+ **Q: How do I avoid accidental key collisions?**
317
+ Prefix keys by domain (e.g. `user:profile`, `cart:items`) or rely on provider scoping.
318
+
319
+ **Q: Why is my async function not re-running?**
320
+ It's cached. Use `forceTrigger()` or `clear()`.
321
+
322
+ **Q: Can I use it with Suspense?**
323
+ Currently no built-in Suspense wrappers; wrap `useSharedFunction` yourself if desired.
324
+
325
+
326
+ ## 📚 Full API Reference
327
+ ### `useSharedState(key, initialValue, scopeName?)`
328
+ Returns `[value, setValue]`.
329
+
330
+ ### `useSharedFunction(key, fn, scopeName?)`
331
+ Returns `{ state, trigger, forceTrigger, clear }`.
332
+
333
+ ### `<SharedStatesProvider scopeName?>`
334
+ Wrap children; optional `scopeName` (string). If omitted a random unique one is generated.
335
+
336
+ ### Static
337
+ `sharedStatesApi`, `sharedFunctionsApi` (see earlier table).
338
+
339
+
340
+
341
+ ## 🤝 Contributions
342
+
343
+ We welcome contributions!
344
+ If you'd like to improve `react-shared-states`,
345
+ feel free to [open an issue](https://github.com/HichemTab-tech/react-shared-states/issues) or [submit a pull request](https://github.com/HichemTab-tech/react-shared-states/pulls).
346
+
347
+
348
+ ## Author
349
+
350
+ - [@HichemTab-tech](https://www.github.com/HichemTab-tech)
351
+
352
+ ## License
353
+
354
+ [MIT](https://github.com/HichemTab-tech/react-shared-states/blob/master/LICENSE)
355
+
356
+ ## 🌟 Acknowledgements
357
+
358
+ Inspired by React's built-in primitives and the ergonomics of modern lightweight state libraries.
359
+ Thanks to early adopters for feedback.
Binary file
@@ -0,0 +1,25 @@
1
+ import { AFunction, DataMapValue, NonEmptyString, Prefix } from './types';
2
+ type SharedDataType<T> = DataMapValue & T;
3
+ export declare abstract class SharedData<T> {
4
+ data: Map<string, SharedDataType<T>>;
5
+ defaultValue(): T;
6
+ addListener(key: string, prefix: Prefix, listener: AFunction): void;
7
+ removeListener(key: string, prefix: Prefix, listener: AFunction): void;
8
+ callListeners(key: string, prefix: Prefix): void;
9
+ init(key: string, prefix: Prefix, data: T): void;
10
+ clearAll(withoutListeners?: boolean): void;
11
+ clear(key: string, prefix: Prefix, withoutListeners?: boolean): void;
12
+ get(key: string, prefix: Prefix): SharedDataType<T> | undefined;
13
+ setValue(key: string, prefix: Prefix, data: T): void;
14
+ has(key: string, prefix: Prefix): string | undefined;
15
+ static prefix(key: string, prefix: Prefix): string;
16
+ }
17
+ export interface SharedApi<T> {
18
+ get: <S extends string = string>(key: NonEmptyString<S>, scopeName: Prefix) => T;
19
+ set: <S extends string = string>(key: NonEmptyString<S>, value: T, scopeName: Prefix) => void;
20
+ clearAll: () => void;
21
+ clear: (key: string, scopeName: Prefix) => void;
22
+ has: (key: string, scopeName: Prefix) => boolean;
23
+ getAll: () => Map<string, DataMapValue>;
24
+ }
25
+ export {};
@@ -0,0 +1,11 @@
1
+ import { PropsWithChildren } from 'react';
2
+ import { NonEmptyString } from '../types';
3
+ export interface SharedStatesType {
4
+ scopeName: string;
5
+ }
6
+ interface SharedStatesProviderProps<T extends string = string> extends PropsWithChildren {
7
+ scopeName?: '__global' extends NonEmptyString<T> ? never : NonEmptyString<T>;
8
+ }
9
+ export declare const SharedStatesProvider: <T extends string = string>({ children, scopeName }: SharedStatesProviderProps<T>) => import("react/jsx-runtime").JSX.Element;
10
+ export declare const useSharedStatesContext: () => SharedStatesType | undefined;
11
+ export {};
@@ -0,0 +1 @@
1
+ export { SharedStatesProvider, } from './SharedStatesContext';
@@ -0,0 +1,2 @@
1
+ export { useSharedState, sharedStatesApi } from './use-shared-state';
2
+ export { useSharedFunction, sharedFunctionsApi } from './use-shared-function';