@goodnight-dev/react-hooks 0.1.0 → 0.2.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 +27 -7
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +2 -1
- package/dist/use-local-storage.d.mts +33 -0
- package/dist/use-local-storage.mjs +84 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -23,31 +23,51 @@ Requires React `>=19`.
|
|
|
23
23
|
|
|
24
24
|
```ts
|
|
25
25
|
// 1. Barrel — everything from one entry point.
|
|
26
|
-
import { useTheme } from '@goodnight-dev/react-hooks';
|
|
26
|
+
import { useLocalStorage, useTheme } from '@goodnight-dev/react-hooks';
|
|
27
27
|
|
|
28
28
|
// 2. Subpath — smallest possible import, no barrel involved at all.
|
|
29
29
|
import { useTheme } from '@goodnight-dev/react-hooks/useTheme';
|
|
30
|
+
import { useLocalStorage } from '@goodnight-dev/react-hooks/useLocalStorage';
|
|
30
31
|
```
|
|
31
32
|
|
|
32
33
|
Both are fully typed, ESM-only, and tree-shakable.
|
|
33
34
|
|
|
34
35
|
## API
|
|
35
36
|
|
|
36
|
-
| Hook
|
|
37
|
-
|
|
|
38
|
-
| `useTheme()`
|
|
37
|
+
| Hook | Description |
|
|
38
|
+
| ------------------------------- | ---------------------------------------------------------------------------------- |
|
|
39
|
+
| `useTheme()` | Reads the OS `prefers-color-scheme`, live-updating on change. |
|
|
40
|
+
| `useLocalStorage(key, initial)` | Reads and writes a JSON-serializable value in `localStorage`, syncing across tabs. |
|
|
39
41
|
|
|
40
42
|
```tsx
|
|
41
|
-
import { useTheme } from '@goodnight-dev/react-hooks';
|
|
43
|
+
import { useLocalStorage, useTheme } from '@goodnight-dev/react-hooks';
|
|
44
|
+
|
|
45
|
+
// Module scope: created once when this file loads, never re-allocated on
|
|
46
|
+
// render, so there's nothing to memoize.
|
|
47
|
+
const defaultSettings = { seen: false };
|
|
42
48
|
|
|
43
49
|
function App() {
|
|
44
50
|
const { theme, isDarkMode } = useTheme();
|
|
51
|
+
const [settings, setSettings] = useLocalStorage(
|
|
52
|
+
`users-${userId}`,
|
|
53
|
+
defaultSettings,
|
|
54
|
+
);
|
|
55
|
+
|
|
45
56
|
if (theme === undefined) return null; // avoid a flash of the wrong theme
|
|
46
|
-
return
|
|
57
|
+
return (
|
|
58
|
+
<div data-theme={theme}>
|
|
59
|
+
{isDarkMode ? '🌙' : '☀️'}
|
|
60
|
+
<button onClick={() => setSettings((s) => ({ ...s, seen: true }))}>
|
|
61
|
+
Dismiss
|
|
62
|
+
</button>
|
|
63
|
+
</div>
|
|
64
|
+
);
|
|
47
65
|
}
|
|
48
66
|
```
|
|
49
67
|
|
|
50
|
-
See [`src/use-theme.md`](./src/use-theme.md)
|
|
68
|
+
See [`src/use-theme.md`](./src/use-theme.md) and
|
|
69
|
+
[`src/use-local-storage.md`](./src/use-local-storage.md) for the design
|
|
70
|
+
rationale behind each.
|
|
51
71
|
|
|
52
72
|
## Project goals
|
|
53
73
|
|
package/dist/index.d.mts
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
//#region src/use-local-storage.d.ts
|
|
2
|
+
type SetValue<T> = T | ((previous: T) => T);
|
|
3
|
+
/**
|
|
4
|
+
* Read and write a JSON-serializable value in `localStorage`, keyed by
|
|
5
|
+
* `key`, re-rendering on change — including changes made from another tab.
|
|
6
|
+
*
|
|
7
|
+
* Mirrors `useState`'s own `[value, setValue]` shape rather than a
|
|
8
|
+
* mutate-in-place object, so there is exactly one write path to reason
|
|
9
|
+
* about. Backed by `useSyncExternalStore`: `localStorage` is the single
|
|
10
|
+
* source of truth (nothing is cached in React state), so `getSnapshot`
|
|
11
|
+
* re-reads it on every call, and `setValue`'s functional-update form always
|
|
12
|
+
* sees the current stored value, not a stale render's closure.
|
|
13
|
+
*
|
|
14
|
+
* `initialValue` is only ever used the first time a key has nothing stored
|
|
15
|
+
* for it, and — same as `useState` — only its *first* value is honored;
|
|
16
|
+
* passing a new literal on a later render does not overwrite what is
|
|
17
|
+
* already stored, so memoize non-primitive defaults yourself if you want to
|
|
18
|
+
* avoid recreating them every render.
|
|
19
|
+
*
|
|
20
|
+
* @param key - The `localStorage` key. Changing it switches to that key's
|
|
21
|
+
* own value, subscribing and reading independently.
|
|
22
|
+
* @param initialValue - Returned when `key` has nothing stored yet, and
|
|
23
|
+
* used as-is during SSR (there is no `localStorage` on the server).
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```tsx
|
|
27
|
+
* const [settings, setSettings] = useLocalStorage(`users-${userId}`, defaultSettings);
|
|
28
|
+
* setSettings((previous) => ({ ...previous, theme: 'dark' }));
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
declare function useLocalStorage<T>(key: string, initialValue: T): [T, (value: SetValue<T>) => void];
|
|
32
|
+
//#endregion
|
|
33
|
+
export { useLocalStorage };
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { useCallback, useRef, useSyncExternalStore } from "react";
|
|
2
|
+
//#region src/use-local-storage.ts
|
|
3
|
+
const SAME_TAB_EVENT = "goodnight-dev:use-local-storage";
|
|
4
|
+
function readRaw(key) {
|
|
5
|
+
try {
|
|
6
|
+
return window.localStorage.getItem(key);
|
|
7
|
+
} catch {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Read and write a JSON-serializable value in `localStorage`, keyed by
|
|
13
|
+
* `key`, re-rendering on change — including changes made from another tab.
|
|
14
|
+
*
|
|
15
|
+
* Mirrors `useState`'s own `[value, setValue]` shape rather than a
|
|
16
|
+
* mutate-in-place object, so there is exactly one write path to reason
|
|
17
|
+
* about. Backed by `useSyncExternalStore`: `localStorage` is the single
|
|
18
|
+
* source of truth (nothing is cached in React state), so `getSnapshot`
|
|
19
|
+
* re-reads it on every call, and `setValue`'s functional-update form always
|
|
20
|
+
* sees the current stored value, not a stale render's closure.
|
|
21
|
+
*
|
|
22
|
+
* `initialValue` is only ever used the first time a key has nothing stored
|
|
23
|
+
* for it, and — same as `useState` — only its *first* value is honored;
|
|
24
|
+
* passing a new literal on a later render does not overwrite what is
|
|
25
|
+
* already stored, so memoize non-primitive defaults yourself if you want to
|
|
26
|
+
* avoid recreating them every render.
|
|
27
|
+
*
|
|
28
|
+
* @param key - The `localStorage` key. Changing it switches to that key's
|
|
29
|
+
* own value, subscribing and reading independently.
|
|
30
|
+
* @param initialValue - Returned when `key` has nothing stored yet, and
|
|
31
|
+
* used as-is during SSR (there is no `localStorage` on the server).
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```tsx
|
|
35
|
+
* const [settings, setSettings] = useLocalStorage(`users-${userId}`, defaultSettings);
|
|
36
|
+
* setSettings((previous) => ({ ...previous, theme: 'dark' }));
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
function useLocalStorage(key, initialValue) {
|
|
40
|
+
const cacheRef = useRef(null);
|
|
41
|
+
const getSnapshot = useCallback(() => {
|
|
42
|
+
const raw = readRaw(key);
|
|
43
|
+
const cache = cacheRef.current;
|
|
44
|
+
if (cache !== null && cache.raw === raw) return cache.value;
|
|
45
|
+
let value;
|
|
46
|
+
if (raw === null) value = initialValue;
|
|
47
|
+
else try {
|
|
48
|
+
value = JSON.parse(raw);
|
|
49
|
+
} catch {
|
|
50
|
+
value = initialValue;
|
|
51
|
+
}
|
|
52
|
+
cacheRef.current = {
|
|
53
|
+
raw,
|
|
54
|
+
value
|
|
55
|
+
};
|
|
56
|
+
return value;
|
|
57
|
+
}, [key, initialValue]);
|
|
58
|
+
const getServerSnapshot = useCallback(() => initialValue, [initialValue]);
|
|
59
|
+
return [useSyncExternalStore(useCallback((onStoreChange) => {
|
|
60
|
+
const handleStorage = (event) => {
|
|
61
|
+
if (event.key === null || event.key === key) onStoreChange();
|
|
62
|
+
};
|
|
63
|
+
const handleSameTab = (event) => {
|
|
64
|
+
if (event.detail === key) onStoreChange();
|
|
65
|
+
};
|
|
66
|
+
window.addEventListener("storage", handleStorage);
|
|
67
|
+
window.addEventListener(SAME_TAB_EVENT, handleSameTab);
|
|
68
|
+
return () => {
|
|
69
|
+
window.removeEventListener("storage", handleStorage);
|
|
70
|
+
window.removeEventListener(SAME_TAB_EVENT, handleSameTab);
|
|
71
|
+
};
|
|
72
|
+
}, [key]), getSnapshot, getServerSnapshot), useCallback((next) => {
|
|
73
|
+
const resolved = typeof next === "function" ? next(getSnapshot()) : next;
|
|
74
|
+
try {
|
|
75
|
+
window.localStorage.setItem(key, JSON.stringify(resolved));
|
|
76
|
+
} catch (error) {
|
|
77
|
+
console.warn(`useLocalStorage: failed to persist "${key}" to localStorage`, error);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
window.dispatchEvent(new CustomEvent(SAME_TAB_EVENT, { detail: key }));
|
|
81
|
+
}, [key, getSnapshot])];
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
export { useLocalStorage };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodnight-dev/react-hooks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Small, strict, tree-shakeable React hooks — the ones you end up writing in every project, packaged the right way.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -27,6 +27,10 @@
|
|
|
27
27
|
"types": "./dist/index.d.mts",
|
|
28
28
|
"import": "./dist/index.mjs"
|
|
29
29
|
},
|
|
30
|
+
"./useLocalStorage": {
|
|
31
|
+
"types": "./dist/use-local-storage.d.mts",
|
|
32
|
+
"import": "./dist/use-local-storage.mjs"
|
|
33
|
+
},
|
|
30
34
|
"./useTheme": {
|
|
31
35
|
"types": "./dist/use-theme.d.mts",
|
|
32
36
|
"import": "./dist/use-theme.mjs"
|