@goodnight-dev/react-hooks 0.1.0 → 0.3.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 +29 -7
- package/dist/index.d.mts +3 -1
- package/dist/index.mjs +3 -1
- package/dist/use-local-storage.d.mts +33 -0
- package/dist/use-local-storage.mjs +84 -0
- package/dist/use-theme.d.mts +4 -4
- package/dist/use-window-size.d.mts +37 -0
- package/dist/use-window-size.mjs +52 -0
- package/package.json +10 -1
package/README.md
CHANGED
|
@@ -23,31 +23,53 @@ 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. |
|
|
41
|
+
| `useWindowSize()` | Reads the viewport `width` / `height`, live-updating on resize. |
|
|
39
42
|
|
|
40
43
|
```tsx
|
|
41
|
-
import { useTheme } from '@goodnight-dev/react-hooks';
|
|
44
|
+
import { useLocalStorage, useTheme } from '@goodnight-dev/react-hooks';
|
|
45
|
+
|
|
46
|
+
// Module scope: created once when this file loads, never re-allocated on
|
|
47
|
+
// render, so there's nothing to memoize.
|
|
48
|
+
const defaultSettings = { seen: false };
|
|
42
49
|
|
|
43
50
|
function App() {
|
|
44
51
|
const { theme, isDarkMode } = useTheme();
|
|
52
|
+
const [settings, setSettings] = useLocalStorage(
|
|
53
|
+
`users-${userId}`,
|
|
54
|
+
defaultSettings,
|
|
55
|
+
);
|
|
56
|
+
|
|
45
57
|
if (theme === undefined) return null; // avoid a flash of the wrong theme
|
|
46
|
-
return
|
|
58
|
+
return (
|
|
59
|
+
<div data-theme={theme}>
|
|
60
|
+
{isDarkMode ? '🌙' : '☀️'}
|
|
61
|
+
<button onClick={() => setSettings((s) => ({ ...s, seen: true }))}>
|
|
62
|
+
Dismiss
|
|
63
|
+
</button>
|
|
64
|
+
</div>
|
|
65
|
+
);
|
|
47
66
|
}
|
|
48
67
|
```
|
|
49
68
|
|
|
50
|
-
See [`src/use-theme.md`](./src/use-theme.md)
|
|
69
|
+
See [`src/use-theme.md`](./src/use-theme.md),
|
|
70
|
+
[`src/use-local-storage.md`](./src/use-local-storage.md), and
|
|
71
|
+
[`src/use-window-size.md`](./src/use-window-size.md) for the design rationale
|
|
72
|
+
behind each.
|
|
51
73
|
|
|
52
74
|
## Project goals
|
|
53
75
|
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
|
+
import { useLocalStorage } from "./use-local-storage.mjs";
|
|
1
2
|
import { Theme, ThemePreference, useTheme } from "./use-theme.mjs";
|
|
2
|
-
|
|
3
|
+
import { WindowSize, useWindowSize } from "./use-window-size.mjs";
|
|
4
|
+
export { type Theme, type ThemePreference, type WindowSize, useLocalStorage, useTheme, useWindowSize };
|
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/dist/use-theme.d.mts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
//#region src/use-theme.d.ts
|
|
2
2
|
type Theme = 'dark' | 'light';
|
|
3
3
|
interface ThemePreference {
|
|
4
|
-
isDarkMode: boolean;
|
|
5
|
-
isLightMode: boolean;
|
|
4
|
+
readonly isDarkMode: boolean;
|
|
5
|
+
readonly isLightMode: boolean;
|
|
6
6
|
/**
|
|
7
7
|
* `'dark'` or `'light'`, or `undefined` before the client has reported its
|
|
8
8
|
* actual preference (always the case during SSR).
|
|
9
9
|
*/
|
|
10
|
-
theme: Theme | undefined;
|
|
10
|
+
readonly theme: Theme | undefined;
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
13
13
|
* Read the user's OS-level color scheme preference
|
|
@@ -31,6 +31,6 @@ interface ThemePreference {
|
|
|
31
31
|
* return <div data-theme={theme}>{isDarkMode ? '🌙' : '☀️'}</div>;
|
|
32
32
|
* ```
|
|
33
33
|
*/
|
|
34
|
-
declare function useTheme(): ThemePreference
|
|
34
|
+
declare function useTheme(): Readonly<ThemePreference>;
|
|
35
35
|
//#endregion
|
|
36
36
|
export { Theme, ThemePreference, useTheme };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
//#region src/use-window-size.d.ts
|
|
2
|
+
interface WindowSize {
|
|
3
|
+
/**
|
|
4
|
+
* The viewport width in CSS pixels, or `undefined` before the client has
|
|
5
|
+
* reported its actual size (always the case during SSR).
|
|
6
|
+
*/
|
|
7
|
+
readonly width: number | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* The viewport height in CSS pixels, or `undefined` before the client has
|
|
10
|
+
* reported its actual size (always the case during SSR).
|
|
11
|
+
*/
|
|
12
|
+
readonly height: number | undefined;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Read the browser viewport's `width` and `height` (in CSS pixels), staying
|
|
16
|
+
* in sync as the window is resized.
|
|
17
|
+
*
|
|
18
|
+
* Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
|
|
19
|
+
* and does not tear. `width` and `height` are `undefined` on the server —
|
|
20
|
+
* and on the client until the first resize-store read commits — the same
|
|
21
|
+
* "unknown until proven otherwise" contract `useTheme` uses for `theme`,
|
|
22
|
+
* applied to both fields here since neither has a safe default to guess.
|
|
23
|
+
*
|
|
24
|
+
* @returns `width` and `height` in CSS pixels, each `undefined` until the
|
|
25
|
+
* client has reported the real viewport size. The returned object is
|
|
26
|
+
* memoized, so its identity only changes when a dimension does.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```tsx
|
|
30
|
+
* const { width, height } = useWindowSize();
|
|
31
|
+
* if (width === undefined || height === undefined) return null; // avoid laying out against an unknown size
|
|
32
|
+
* return <div>{width} × {height}</div>;
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
declare function useWindowSize(): Readonly<WindowSize>;
|
|
36
|
+
//#endregion
|
|
37
|
+
export { WindowSize, useWindowSize };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { useCallback, useRef, useSyncExternalStore } from "react";
|
|
2
|
+
//#region src/use-window-size.ts
|
|
3
|
+
const SERVER_SNAPSHOT = {
|
|
4
|
+
width: void 0,
|
|
5
|
+
height: void 0
|
|
6
|
+
};
|
|
7
|
+
const getServerSnapshot = () => SERVER_SNAPSHOT;
|
|
8
|
+
const subscribe = (onStoreChange) => {
|
|
9
|
+
window.addEventListener("resize", onStoreChange);
|
|
10
|
+
return () => {
|
|
11
|
+
window.removeEventListener("resize", onStoreChange);
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Read the browser viewport's `width` and `height` (in CSS pixels), staying
|
|
16
|
+
* in sync as the window is resized.
|
|
17
|
+
*
|
|
18
|
+
* Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
|
|
19
|
+
* and does not tear. `width` and `height` are `undefined` on the server —
|
|
20
|
+
* and on the client until the first resize-store read commits — the same
|
|
21
|
+
* "unknown until proven otherwise" contract `useTheme` uses for `theme`,
|
|
22
|
+
* applied to both fields here since neither has a safe default to guess.
|
|
23
|
+
*
|
|
24
|
+
* @returns `width` and `height` in CSS pixels, each `undefined` until the
|
|
25
|
+
* client has reported the real viewport size. The returned object is
|
|
26
|
+
* memoized, so its identity only changes when a dimension does.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```tsx
|
|
30
|
+
* const { width, height } = useWindowSize();
|
|
31
|
+
* if (width === undefined || height === undefined) return null; // avoid laying out against an unknown size
|
|
32
|
+
* return <div>{width} × {height}</div>;
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
function useWindowSize() {
|
|
36
|
+
const cacheRef = useRef(null);
|
|
37
|
+
const getSnapshot = useCallback(() => {
|
|
38
|
+
const width = window.innerWidth;
|
|
39
|
+
const height = window.innerHeight;
|
|
40
|
+
const cache = cacheRef.current;
|
|
41
|
+
if (cache !== null && cache.width === width && cache.height === height) return cache;
|
|
42
|
+
const next = {
|
|
43
|
+
width,
|
|
44
|
+
height
|
|
45
|
+
};
|
|
46
|
+
cacheRef.current = next;
|
|
47
|
+
return next;
|
|
48
|
+
}, []);
|
|
49
|
+
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
export { useWindowSize };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodnight-dev/react-hooks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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,10 +27,18 @@
|
|
|
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"
|
|
33
37
|
},
|
|
38
|
+
"./useWindowSize": {
|
|
39
|
+
"types": "./dist/use-window-size.d.mts",
|
|
40
|
+
"import": "./dist/use-window-size.mjs"
|
|
41
|
+
},
|
|
34
42
|
"./package.json": "./package.json"
|
|
35
43
|
},
|
|
36
44
|
"files": [
|
|
@@ -59,6 +67,7 @@
|
|
|
59
67
|
"esbuild": "^0.28.1",
|
|
60
68
|
"eslint": "^10.6.0",
|
|
61
69
|
"eslint-config-prettier": "^10.1.8",
|
|
70
|
+
"eslint-plugin-functional": "^10.0.0",
|
|
62
71
|
"eslint-plugin-perfectionist": "^5.9.1",
|
|
63
72
|
"eslint-plugin-react-hooks": "^7.1.0",
|
|
64
73
|
"globals": "^17.7.0",
|