Skip to content

Commit 4ab636e

Browse files
authored
Merge pull request #35 from react18-tools/feature/selectors
Feature/selectors
2 parents 07c6aad + 9de6342 commit 4ab636e

38 files changed

+665
-151
lines changed

.github/workflows/docs.yml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,6 @@ jobs:
2929
git pull
3030
- run: npm i -g pnpm && pnpm i
3131
name: Install dependencies
32-
- name: Test
33-
run: npm test
3432
- run: git stash --include-untracked
3533
name: clean up working directory
3634
- run: npx @turbo/codemod update . && pnpm update --latest -r

.github/workflows/test.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ jobs:
1717
- run: npm i -g pnpm && pnpm i
1818
name: Install dependencies
1919
- name: Run unit tests
20-
run: pnpm test
20+
run: cd lib && pnpm test
2121
- name: Upload coverage reports to Codecov
2222
continue-on-error: true
2323
uses: codecov/codecov-action@v4

README.md

Lines changed: 41 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,90 @@
11
# React18GlobalStore <img src="https://raw.githubusercontent.com/mayank1513/mayank1513/main/popper.png" style="height: 40px"/>
22

3-
[![test](https://github.com/react18-tools/react18-global-store/actions/workflows/test.yml/badge.svg)](https://github.com/react18-tools/react18-global-store/actions/workflows/test.yml) [![Maintainability](https://api.codeclimate.com/v1/badges/ec3140063acd8df82481/maintainability)](https://codeclimate.com/github/react18-tools/react18-global-store/maintainability) [![codecov](https://codecov.io/gh/react18-tools/react18-global-store/graph/badge.svg)](https://codecov.io/gh/react18-tools/react18-global-store) [![Version](https://img.shields.io/npm/v/r18gs.svg?colorB=green)](https://www.npmjs.com/package/r18gs) [![Downloads](https://img.jsdelivr.com/img.shields.io/npm/d18m/r18gs.svg)](https://www.npmjs.com/package/r18gs) ![npm bundle size](https://img.shields.io/bundlephobia/minzip/r18gs) [![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/from-referrer/)
3+
[![Test](https://github.com/react18-tools/react18-global-store/actions/workflows/test.yml/badge.svg)](https://github.com/react18-tools/react18-global-store/actions/workflows/test.yml)
4+
[![Maintainability](https://api.codeclimate.com/v1/badges/ec3140063acd8df82481/maintainability)](https://codeclimate.com/github/react18-tools/react18-global-store/maintainability)
5+
[![Code Coverage](https://codecov.io/gh/react18-tools/react18-global-store/graph/badge.svg)](https://codecov.io/gh/react18-tools/react18-global-store)
6+
[![Version](https://img.shields.io/npm/v/r18gs.svg?colorB=green)](https://www.npmjs.com/package/r18gs)
7+
[![Downloads](https://img.jsdelivr.com/img.shields.io/npm/d18m/r18gs.svg)](https://www.npmjs.com/package/r18gs)
8+
![Bundle Size](https://img.shields.io/bundlephobia/minzip/r18gs)
9+
[![Gitpod Ready](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/from-referrer/)
410

5-
## Motivation
6-
7-
I've developed fantastic libraries leveraging React18 features using Zustand, and they performed admirably. However, when attempting to import from specific folders for better tree-shaking, the libraries encountered issues. Each import resulted in a separate Zustand store being created, leading to increased package size.
11+
> 🌐 **Live Demo with Code**: [https://r18gs.vercel.app/](https://r18gs.vercel.app/)
812
9-
As a solution, I set out to create a lightweight, bare minimum store that facilitates shared state even when importing components from separate files, optimizing tree-shaking.
13+
## Motivation
1014

11-
### Important Announcement
15+
While developing libraries utilizing React 18 features with Zustand, I encountered issues with tree-shaking when importing from specific folders. This caused the creation of multiple Zustand stores, resulting in bugs and unnecessary JavaScript code execution.
1216

13-
The default export from `r18gs` is [deprecated](https://github.com/react18-tools/react18-global-store/discussions/31). Please switch to using `import { useRGS } from "r18gs"` instead. The default export will be removed in the next major release.
17+
To address this, I created a lightweight, minimalistic store designed for shared states that optimizes tree-shaking and supports component imports from separate files.
1418

1519
## Features
1620

17-
✅ Full TypeScript Support
18-
19-
✅ Unleash the full power of React18 Server components
20-
21-
✅ Compatible with all build systems/tools/frameworks for React18
21+
**Full TypeScript Support**
22+
**Unlock the Full Power of React18 Server Components**
23+
**Compatible with All React18 Build Systems and Frameworks**
24+
**Comprehensive Documentation with [Typedoc](https://react18-tools.github.io/react18-global-store)**
25+
**Examples for Next.js, Vite, and Remix**
26+
**Seamlessly Works with Selectors**
2227

23-
✅ Documented with [Typedoc](https://react18-tools.github.io/react18-global-store) ([Docs](https://react18-tools.github.io/react18-global-store))
28+
## Simple Global State Across Components
2429

25-
✅ Examples for Next.js, Vite, and Remix
26-
27-
## Simple Global State Shared Across Multiple Components
28-
29-
Utilize this hook similarly to the `useState` hook. However, ensure to pass a unique key, unique across the app, to identify and make this state accessible to all client components.
30+
Use the `useRGS` hook just like `useState`, but with a unique key to make the state accessible across components.
3031

3132
```tsx
3233
const [state, setState] = useRGS<number>("counter", 1);
3334
```
3435

35-
**_or_**
36+
Or initialize using a function:
3637

3738
```tsx
3839
const [state, setState] = useRGS<number>("counter", () => 1);
3940
```
4041

41-
> For detailed instructions, see [Getting Started](./md-docs/1.getting-started.md)
42+
> 🔗 **Getting Started**: [Guide](./md-docs/1.getting-started.md)
43+
44+
## What's New?
45+
46+
🚀 **Now Supports Selectors for Complex Stores**
47+
Explore more at [https://r18gs.vercel.app/](https://r18gs.vercel.app/).
4248

4349
## Using Plugins
4450

45-
Enhance the functionality of the store by leveraging either the `create` function, `withPlugins` function, or the `useRGSWithPlugins` hook from `r18gs/dist/with-plugins`, enabling features such as storing to local storage, among others.
51+
Extend the store's functionality with the `create` function, `withPlugins` function, or the `useRGSWithPlugins` hook. Features like persistence to local storage can be easily integrated.
4652

4753
```tsx
4854
// store.ts
4955
import { create } from "r18gs/dist/with-plugins";
50-
import { persist } from "r18gs/dist/plugins"; /** You can create your own plugin or import third-party plugins */
56+
import { persist } from "r18gs/dist/plugins"; // Use third-party or custom plugins
5157

5258
export const useMyPersistentCounterStore = create<number>("persistent-counter", 0, [persist()]);
5359
```
5460

55-
Now, you can utilize `useMyPersistentCounterStore` similarly to `useState` without specifying an initial value.
61+
Use it just like `useState` without needing an initial value:
5662

5763
```tsx
5864
const [persistedCount, setPersistedCount] = useMyPersistentCounterStore();
5965
```
6066

61-
> For detailed instructions, see [Leveraging Plugins](./md-docs/2.leveraging-plugins.md)
67+
> 🔗 **Learn More**: [Leveraging Plugins](./md-docs/2.leveraging-plugins.md)
6268
6369
## Contributing
6470

65-
See [contributing.md](/contributing.md)
71+
Contributions are welcome! See [contributing.md](/contributing.md).
72+
73+
### 🌟 Don't Forget to Star [this repository](https://github.com/mayank1513/react18-global-store)!
6674

67-
### 🤩 Don't forget to star [this repo](https://github.com/mayank1513/react18-global-store)!
75+
### Hands-On Learning Resources
6876

69-
Interested in hands-on courses for getting started with Turborepo? Check out [React and Next.js with TypeScript](https://mayank-chaudhari.vercel.app/courses/react-and-next-js-with-typescript) and [The Game of Chess with Next.js, React and TypeScript](https://www.udemy.com/course/game-of-chess-with-nextjs-react-and-typescript/?referralCode=851A28F10B254A8523FE)
77+
- [React and Next.js with TypeScript](https://mayank-chaudhari.vercel.app/courses/react-and-next-js-with-typescript)
78+
- [The Game of Chess with Next.js, React, and TypeScript](https://www.udemy.com/course/game-of-chess-with-nextjs-react-and-typescript/?referralCode=851A28F10B254A8523FE)
7079

71-
![Repo Stats](https://repobeats.axiom.co/api/embed/ec3e74d795ed805a0fce67c0b64c3f08872e7945.svg "Repobeats analytics image")
80+
![Repo Stats](https://repobeats.axiom.co/api/embed/ec3e74d795ed805a0fce67c0b64c3f08872e7945.svg "Repobeats Analytics")
7281

7382
## License
7483

75-
This library is licensed under the MPL-2.0 open-source license.
84+
This library is licensed under the **MPL-2.0** open-source license.
7685

77-
> <img src="https://raw.githubusercontent.com/mayank1513/mayank1513/main/popper.png" style="height: 20px"/> Please consider enrolling in [our courses](https://mayank-chaudhari.vercel.app/courses) or [sponsoring](https://github.com/sponsors/mayank1513) our work.
86+
> <img src="https://raw.githubusercontent.com/mayank1513/mayank1513/main/popper.png" style="height: 20px"/> Support our work by [sponsoring](https://github.com/sponsors/mayank1513) or enrolling in [our courses](https://mayank-chaudhari.vercel.app/courses).
7887
79-
<hr />
88+
---
8089

81-
<p align="center" style="text-align:center">with 💖 by <a href="https://mayank-chaudhari.vercel.app" target="_blank">Mayank Kumar Chaudhari</a></p>
90+
<p align="center" style="text-align:center">Made with 💖 by <a href="https://mayank-chaudhari.vercel.app" target="_blank">Mayank Kumar Chaudhari</a></p>

examples/nextjs/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"@repo/shared": "workspace:*",
1515
"next": "^15.1.0",
1616
"nextjs-darkmode": "^1.0.7",
17+
"nextjs-darkmode-lite": "^1.0.7",
1718
"nextjs-themes": "^4.0.4",
1819
"r18gs": "workspace:*",
1920
"react": "^19.0.0",

lib/CHANGELOG.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
# r18gs
22

3+
## 2.1.0
4+
5+
### Minor Changes
6+
7+
- 22efc00: Add selectors - do not unnecessarily re-render the components.
8+
9+
### Patch Changes
10+
11+
- a05da0e: Improve type safety
12+
313
## 2.0.1
414

515
### Patch Changes

lib/package.json

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "r18gs",
33
"author": "Mayank Kumar Chaudhari <https://mayank-chaudhari.vercel.app>",
44
"private": false,
5-
"version": "2.0.1",
5+
"version": "2.1.0",
66
"description": "A simple yet elegant, light weight, react18 global store to replace Zustand for better tree shaking.",
77
"license": "MPL-2.0",
88
"main": "./dist/index.js",
@@ -46,11 +46,6 @@
4646
"@types/react": "16.8 - 19",
4747
"react": "16.8 - 19"
4848
},
49-
"peerDependenciesMeta": {
50-
"next": {
51-
"optional": true
52-
}
53-
},
5449
"funding": [
5550
{
5651
"type": "github",

lib/src/index.ts

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/* eslint-disable @typescript-eslint/non-nullable-type-assertion-style -- as ! operator is forbidden by eslint*/
2-
import { createHook, createSetter, createSubcriber, globalRGS } from "./utils";
2+
import { createHook, globalRGS, triggerListeners } from "./utils";
33

4-
import type { SetStateAction, ValueType } from "./utils";
4+
import type { RGS, SetStateAction, ValueType } from "./utils";
55

66
export type { SetterArgType, SetStateAction, Plugin } from "./utils";
77

@@ -20,18 +20,25 @@ export type { SetterArgType, SetStateAction, Plugin } from "./utils";
2020
* @param value - Initial value of the store.
2121
* @returns - A tuple (Ordered sequance of values) containing the state and a function to set the state.
2222
*/
23-
const useRGS = <T>(key: string, value?: ValueType<T>): [T, SetStateAction<T>] => {
23+
const useRGS = <T>(
24+
key: string,
25+
value?: ValueType<T>,
26+
...fields: (keyof T)[]
27+
): [T, SetStateAction<T>] => {
2428
/** Initialize the named store when invoked for the first time. */
2529
if (!globalRGS[key])
2630
globalRGS[key] = {
27-
// @ts-expect-error -- ok
28-
v: typeof value === "function" ? value() : value,
31+
v: value instanceof Function ? value() : value,
2932
l: [],
30-
s: createSetter(key),
31-
u: createSubcriber(key),
33+
s: val => {
34+
const rgs = globalRGS[key] as RGS;
35+
const oldV = rgs.v as T;
36+
rgs.v = val instanceof Function ? val(oldV) : val;
37+
triggerListeners(rgs, oldV, rgs.v);
38+
},
3239
};
3340

34-
return createHook<T>(key);
41+
return createHook<T>(key, fields);
3542
};
3643

3744
export { useRGS };

lib/src/utils.ts

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { useSyncExternalStore } from "react";
22

3+
export type Selector = string | number | Symbol;
34
type Listener = () => void;
4-
type Subscriber = (l: Listener) => () => void;
5+
type ListenerWithSelectors = { l: Listener; s: Selector[] };
56

67
export type SetterArgType<T> = T | ((prevState: T) => T);
78
export type SetStateAction<T> = (value: SetterArgType<T>) => void;
@@ -10,7 +11,11 @@ export type ValueType<T> = T | (() => T);
1011
/**
1112
* This is a hack to reduce lib size + readability + not encouraging direct access to globalThis
1213
*/
13-
type RGS = { v: unknown; l: Listener[]; s: SetStateAction<unknown> | null; u: Subscriber };
14+
export type RGS = {
15+
v: unknown;
16+
l: ListenerWithSelectors[];
17+
s: SetStateAction<unknown> | null;
18+
};
1419

1520
declare global {
1621
// eslint-disable-next-line no-var -- var required for global declaration.
@@ -23,34 +28,30 @@ if (!globalThisForBetterMinification.rgs) globalThisForBetterMinification.rgs =
2328
export const globalRGS = globalThisForBetterMinification.rgs;
2429

2530
/** trigger all listeners */
26-
const triggerListeners = (rgs: RGS) => rgs.l.forEach(listener => listener());
27-
28-
/** craete subscriber function to subscribe to the store. */
29-
export const createSubcriber = (key: string): Subscriber => {
30-
return listener => {
31-
const rgs = globalRGS[key] as RGS;
32-
(rgs.l as Listener[]).push(listener);
33-
return () => {
34-
rgs.l = (rgs.l as Listener[]).filter(l => l !== listener);
35-
};
36-
};
37-
};
38-
39-
/** setter function to set the state. */
40-
export const createSetter = <T>(key: string): SetStateAction<unknown> => {
41-
return val => {
42-
const rgs = globalRGS[key] as RGS;
43-
rgs.v = typeof val === "function" ? val(rgs.v as T) : val;
44-
(rgs.l as Listener[]).forEach(listener => listener());
45-
};
31+
export const triggerListeners = <T>(rgs: RGS, oldV: T, newV: T) => {
32+
const updatedFiels: Selector[] = [];
33+
// no need to test this --- it will automatically fail
34+
// if (typeof oldV === "object" && typeof rgs.v === "object")
35+
for (const key in oldV) if (oldV[key] !== newV[key]) updatedFiels.push(key);
36+
rgs.l.forEach(({ l, s }) => (!s.length || s.some(filed => updatedFiels.includes(filed))) && l());
4637
};
4738

4839
/** Extract coomon create hook logic to utils */
49-
export const createHook = <T>(key: string): [T, SetStateAction<T>] => {
40+
export const createHook = <T>(key: string, fields: (keyof T)[]): [T, SetStateAction<T>] => {
5041
const rgs = globalRGS[key] as RGS;
5142
/** This function is called by react to get the current stored value. */
5243
const getSnapshot = () => rgs.v as T;
53-
const val = useSyncExternalStore<T>(rgs.u as Subscriber, getSnapshot, getSnapshot);
44+
const val = useSyncExternalStore<T>(
45+
listener => {
46+
const listenerWithSelectors = { l: listener, s: fields };
47+
rgs.l.push(listenerWithSelectors);
48+
return () => {
49+
rgs.l = rgs.l.filter(l => l !== listenerWithSelectors);
50+
};
51+
},
52+
getSnapshot,
53+
getSnapshot,
54+
);
5455
return [val, rgs.s as SetStateAction<T>];
5556
};
5657

@@ -67,8 +68,9 @@ const initPlugins = async <T>(key: string, plugins: Plugin<T>[]) => {
6768
const rgs = globalRGS[key] as RGS;
6869
/** Mutate function to update the value */
6970
const mutate: Mutate<T> = newValue => {
71+
const oldValue = rgs.v as T;
7072
rgs.v = newValue;
71-
triggerListeners(rgs);
73+
triggerListeners(rgs, oldValue, newValue);
7274
};
7375
for (const plugin of plugins) {
7476
/** Next plugins initializer will get the new value if updated by previous one */
@@ -87,24 +89,25 @@ export const initWithPlugins = <T>(
8789
value = value instanceof Function ? value() : value;
8890
if (doNotInit) {
8991
/** You will not have access to the setter until initialized */
90-
globalRGS[key] = { v: value, l: [], s: null, u: createSubcriber(key) };
92+
globalRGS[key] = { v: value, l: [], s: null };
9193
return;
9294
}
9395
/** setter function to set the state. */
9496
const setterWithPlugins: SetStateAction<unknown> = val => {
9597
/** Do not allow mutating the store before all extentions are initialized */
9698
if (!allExtentionsInitialized) return;
9799
const rgs = globalRGS[key] as RGS;
98-
rgs.v = val instanceof Function ? val(rgs.v as T) : val;
99-
triggerListeners(rgs);
100+
const oldValue = rgs.v;
101+
rgs.v = val instanceof Function ? val(oldValue) : val;
102+
triggerListeners(rgs, oldValue, rgs.v);
100103
plugins.forEach(plugin => plugin.onChange?.(key, rgs.v as T));
101104
};
102105

103106
const rgs = globalRGS[key];
104107
if (rgs) {
105108
rgs.v = value;
106109
rgs.s = setterWithPlugins;
107-
} else globalRGS[key] = { v: value, l: [], s: setterWithPlugins, u: createSubcriber(key) };
110+
} else globalRGS[key] = { v: value, l: [], s: setterWithPlugins };
108111
initPlugins(key, plugins);
109112
};
110113

@@ -130,7 +133,8 @@ export const useRGSWithPlugins = <T>(
130133
value?: ValueType<T>,
131134
plugins?: Plugin<T>[],
132135
doNotInit = false,
136+
...fields: (keyof T)[]
133137
): [T, SetStateAction<T>] => {
134138
if (!globalRGS[key]?.s) initWithPlugins(key, value, plugins, doNotInit);
135-
return createHook<T>(key);
139+
return createHook<T>(key, fields);
136140
};

lib/tests/declarations.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
declare module "*.module.scss";

lib/tests/demo.module.scss

Whitespace-only changes.

0 commit comments

Comments
 (0)