@goodnight-dev/react-hooks 0.3.0 → 0.5.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 CHANGED
@@ -8,8 +8,8 @@ project, packaged the right way.
8
8
  [![docs](https://img.shields.io/badge/docs-online-blue)](https://goodnight-dev.github.io/react-hooks/)
9
9
 
10
10
  > **Status:** bootstrapping — the packaging, CI, docs, and release pipeline are
11
- > in place; the hook surface is still one hook and growing. As much a showcase
12
- > of hook-packaging best practices as a hooks library.
11
+ > in place; the hook surface is still small and growing. As much a showcase of
12
+ > hook-packaging best practices as a hooks library.
13
13
 
14
14
  ## Install
15
15
 
@@ -34,11 +34,13 @@ Both are fully typed, ESM-only, and tree-shakable.
34
34
 
35
35
  ## API
36
36
 
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. |
37
+ | Hook | Description |
38
+ | ------------------------------- | ------------------------------------------------------------------------------------------ |
39
+ | `useTheme()` | Reads the OS `prefers-color-scheme`, live-updating on change. |
40
+ | `useMediaQuery(query)` | Reads any CSS media query (`matchMedia`), live-updating — the primitive behind `useTheme`. |
41
+ | `useLocalStorage(key, initial)` | Reads and writes a JSON-serializable value in `localStorage`, syncing across tabs. |
42
+ | `useWindowSize()` | Reads the viewport `width` / `height`, live-updating on resize. |
43
+ | `useOnlineStatus()` | Reads whether the browser is online (`navigator.onLine`), live-updating. |
42
44
 
43
45
  ```tsx
44
46
  import { useLocalStorage, useTheme } from '@goodnight-dev/react-hooks';
@@ -67,9 +69,11 @@ function App() {
67
69
  ```
68
70
 
69
71
  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.
72
+ [`src/use-media-query.md`](./src/use-media-query.md),
73
+ [`src/use-local-storage.md`](./src/use-local-storage.md),
74
+ [`src/use-window-size.md`](./src/use-window-size.md), and
75
+ [`src/use-online-status.md`](./src/use-online-status.md) for the design
76
+ rationale behind each.
73
77
 
74
78
  ## Project goals
75
79
 
package/dist/index.d.mts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { useLocalStorage } from "./use-local-storage.mjs";
2
+ import { useMediaQuery } from "./use-media-query.mjs";
3
+ import { useOnlineStatus } from "./use-online-status.mjs";
2
4
  import { Theme, ThemePreference, useTheme } from "./use-theme.mjs";
3
5
  import { WindowSize, useWindowSize } from "./use-window-size.mjs";
4
- export { type Theme, type ThemePreference, type WindowSize, useLocalStorage, useTheme, useWindowSize };
6
+ export { type Theme, type ThemePreference, type WindowSize, useLocalStorage, useMediaQuery, useOnlineStatus, useTheme, useWindowSize };
package/dist/index.mjs CHANGED
@@ -1,4 +1,6 @@
1
1
  import { useLocalStorage } from "./use-local-storage.mjs";
2
+ import { useMediaQuery } from "./use-media-query.mjs";
3
+ import { useOnlineStatus } from "./use-online-status.mjs";
2
4
  import { useTheme } from "./use-theme.mjs";
3
5
  import { useWindowSize } from "./use-window-size.mjs";
4
- export { useLocalStorage, useTheme, useWindowSize };
6
+ export { useLocalStorage, useMediaQuery, useOnlineStatus, useTheme, useWindowSize };
@@ -1,4 +1,3 @@
1
- //#region src/use-local-storage.d.ts
2
1
  type SetValue<T> = T | ((previous: T) => T);
3
2
  /**
4
3
  * Read and write a JSON-serializable value in `localStorage`, keyed by
@@ -28,6 +27,5 @@ type SetValue<T> = T | ((previous: T) => T);
28
27
  * setSettings((previous) => ({ ...previous, theme: 'dark' }));
29
28
  * ```
30
29
  */
31
- declare function useLocalStorage<T>(key: string, initialValue: T): [T, (value: SetValue<T>) => void];
32
- //#endregion
33
- export { useLocalStorage };
30
+ export declare function useLocalStorage<T>(key: string, initialValue: T): [T, (value: SetValue<T>) => void];
31
+ export {};
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useRef, useSyncExternalStore } from "react";
2
- //#region src/use-local-storage.ts
2
+ // src/use-local-storage.ts
3
3
  const SAME_TAB_EVENT = "goodnight-dev:use-local-storage";
4
4
  function readRaw(key) {
5
5
  try {
@@ -56,7 +56,7 @@ function useLocalStorage(key, initialValue) {
56
56
  return value;
57
57
  }, [key, initialValue]);
58
58
  const getServerSnapshot = useCallback(() => initialValue, [initialValue]);
59
- return [useSyncExternalStore(useCallback((onStoreChange) => {
59
+ const subscribe = useCallback((onStoreChange) => {
60
60
  const handleStorage = (event) => {
61
61
  if (event.key === null || event.key === key) onStoreChange();
62
62
  };
@@ -69,7 +69,8 @@ function useLocalStorage(key, initialValue) {
69
69
  window.removeEventListener("storage", handleStorage);
70
70
  window.removeEventListener(SAME_TAB_EVENT, handleSameTab);
71
71
  };
72
- }, [key]), getSnapshot, getServerSnapshot), useCallback((next) => {
72
+ }, [key]);
73
+ return [useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot), useCallback((next) => {
73
74
  const resolved = typeof next === "function" ? next(getSnapshot()) : next;
74
75
  try {
75
76
  window.localStorage.setItem(key, JSON.stringify(resolved));
@@ -80,5 +81,4 @@ function useLocalStorage(key, initialValue) {
80
81
  window.dispatchEvent(new CustomEvent(SAME_TAB_EVENT, { detail: key }));
81
82
  }, [key, getSnapshot])];
82
83
  }
83
- //#endregion
84
84
  export { useLocalStorage };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Read whether a CSS media query currently matches
3
+ * (`window.matchMedia(query).matches`), staying in sync as it starts and stops
4
+ * matching.
5
+ *
6
+ * The general form of a `matchMedia` subscription — breakpoints
7
+ * (`'(min-width: 768px)'`), `'(prefers-reduced-motion: reduce)'`, pointer /
8
+ * hover capability, `'print'`, and so on. `useTheme` is this hook specialized
9
+ * to `'(prefers-color-scheme: dark)'`.
10
+ *
11
+ * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
12
+ * and does not tear. The result is `undefined` on the server — and on the
13
+ * client until the first `matchMedia` read commits — the same "unknown until
14
+ * proven otherwise" contract `useTheme` uses for `theme`: there is no honest
15
+ * value to render for a query the server cannot evaluate, so render a neutral
16
+ * state for `undefined` rather than guessing a match.
17
+ *
18
+ * `query` should be a stable string; changing it re-subscribes to the new
19
+ * query (and re-reads), the same way passing a new `key` to `useLocalStorage`
20
+ * switches keys.
21
+ *
22
+ * @param query - A media query string, exactly as `window.matchMedia` takes it.
23
+ *
24
+ * @returns `true` when the query matches, `false` when it does not, and
25
+ * `undefined` until the client has read the real value (always the case during
26
+ * SSR).
27
+ *
28
+ * @example
29
+ * ```tsx
30
+ * const isWide = useMediaQuery('(min-width: 768px)');
31
+ * if (isWide === undefined) return null; // don't guess a breakpoint before we know
32
+ * return isWide ? <Sidebar /> : <Drawer />;
33
+ * ```
34
+ */
35
+ export declare function useMediaQuery(query: string): boolean | undefined;
@@ -0,0 +1,49 @@
1
+ import { useCallback, useSyncExternalStore } from "react";
2
+ // src/use-media-query.ts
3
+ const getServerSnapshot = () => void 0;
4
+ /**
5
+ * Read whether a CSS media query currently matches
6
+ * (`window.matchMedia(query).matches`), staying in sync as it starts and stops
7
+ * matching.
8
+ *
9
+ * The general form of a `matchMedia` subscription — breakpoints
10
+ * (`'(min-width: 768px)'`), `'(prefers-reduced-motion: reduce)'`, pointer /
11
+ * hover capability, `'print'`, and so on. `useTheme` is this hook specialized
12
+ * to `'(prefers-color-scheme: dark)'`.
13
+ *
14
+ * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
15
+ * and does not tear. The result is `undefined` on the server — and on the
16
+ * client until the first `matchMedia` read commits — the same "unknown until
17
+ * proven otherwise" contract `useTheme` uses for `theme`: there is no honest
18
+ * value to render for a query the server cannot evaluate, so render a neutral
19
+ * state for `undefined` rather than guessing a match.
20
+ *
21
+ * `query` should be a stable string; changing it re-subscribes to the new
22
+ * query (and re-reads), the same way passing a new `key` to `useLocalStorage`
23
+ * switches keys.
24
+ *
25
+ * @param query - A media query string, exactly as `window.matchMedia` takes it.
26
+ *
27
+ * @returns `true` when the query matches, `false` when it does not, and
28
+ * `undefined` until the client has read the real value (always the case during
29
+ * SSR).
30
+ *
31
+ * @example
32
+ * ```tsx
33
+ * const isWide = useMediaQuery('(min-width: 768px)');
34
+ * if (isWide === undefined) return null; // don't guess a breakpoint before we know
35
+ * return isWide ? <Sidebar /> : <Drawer />;
36
+ * ```
37
+ */
38
+ function useMediaQuery(query) {
39
+ const subscribe = useCallback((onStoreChange) => {
40
+ const mediaQueryList = window.matchMedia(query);
41
+ mediaQueryList.addEventListener("change", onStoreChange);
42
+ return () => {
43
+ mediaQueryList.removeEventListener("change", onStoreChange);
44
+ };
45
+ }, [query]);
46
+ const getSnapshot = useCallback(() => window.matchMedia(query).matches, [query]);
47
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
48
+ }
49
+ export { useMediaQuery };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Read whether the browser currently has a network connection
3
+ * (`navigator.onLine`), staying in sync as it connects and disconnects.
4
+ *
5
+ * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
6
+ * and does not tear. The value is `undefined` on the server — and on the
7
+ * client until the first `navigator.onLine` read commits — the same "unknown
8
+ * until proven otherwise" contract `useTheme` uses for `theme`: there is no
9
+ * honest value to render for a client whose connectivity the server cannot
10
+ * know, so render a neutral state for `undefined` rather than assuming online.
11
+ *
12
+ * `navigator.onLine` is necessary but not sufficient: `false` means the
13
+ * browser knows it is offline, but `true` only means it has *a* network
14
+ * interface, not that the internet is actually reachable — a captive portal
15
+ * or a dead upstream link still reads `true`. Treat it as "definitely
16
+ * offline" vs. "probably online," not a reachability check; confirm with a
17
+ * real request if you need certainty.
18
+ *
19
+ * @returns `true` when the browser reports a connection, `false` when it
20
+ * reports none, and `undefined` until the client has read the real value
21
+ * (always the case during SSR).
22
+ *
23
+ * @example
24
+ * ```tsx
25
+ * const isOnline = useOnlineStatus();
26
+ * if (isOnline === undefined) return null; // don't assume online before we know
27
+ * return isOnline ? <App /> : <OfflineBanner />;
28
+ * ```
29
+ */
30
+ export declare function useOnlineStatus(): boolean | undefined;
@@ -0,0 +1,45 @@
1
+ import { useSyncExternalStore } from "react";
2
+ // src/use-online-status.ts
3
+ const subscribe = (onStoreChange) => {
4
+ window.addEventListener("online", onStoreChange);
5
+ window.addEventListener("offline", onStoreChange);
6
+ return () => {
7
+ window.removeEventListener("online", onStoreChange);
8
+ window.removeEventListener("offline", onStoreChange);
9
+ };
10
+ };
11
+ const getSnapshot = () => navigator.onLine;
12
+ const getServerSnapshot = () => void 0;
13
+ /**
14
+ * Read whether the browser currently has a network connection
15
+ * (`navigator.onLine`), staying in sync as it connects and disconnects.
16
+ *
17
+ * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
18
+ * and does not tear. The value is `undefined` on the server — and on the
19
+ * client until the first `navigator.onLine` read commits — the same "unknown
20
+ * until proven otherwise" contract `useTheme` uses for `theme`: there is no
21
+ * honest value to render for a client whose connectivity the server cannot
22
+ * know, so render a neutral state for `undefined` rather than assuming online.
23
+ *
24
+ * `navigator.onLine` is necessary but not sufficient: `false` means the
25
+ * browser knows it is offline, but `true` only means it has *a* network
26
+ * interface, not that the internet is actually reachable — a captive portal
27
+ * or a dead upstream link still reads `true`. Treat it as "definitely
28
+ * offline" vs. "probably online," not a reachability check; confirm with a
29
+ * real request if you need certainty.
30
+ *
31
+ * @returns `true` when the browser reports a connection, `false` when it
32
+ * reports none, and `undefined` until the client has read the real value
33
+ * (always the case during SSR).
34
+ *
35
+ * @example
36
+ * ```tsx
37
+ * const isOnline = useOnlineStatus();
38
+ * if (isOnline === undefined) return null; // don't assume online before we know
39
+ * return isOnline ? <App /> : <OfflineBanner />;
40
+ * ```
41
+ */
42
+ function useOnlineStatus() {
43
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
44
+ }
45
+ export { useOnlineStatus };
@@ -1,6 +1,5 @@
1
- //#region src/use-theme.d.ts
2
- type Theme = 'dark' | 'light';
3
- interface ThemePreference {
1
+ export type Theme = 'dark' | 'light';
2
+ export interface ThemePreference {
4
3
  readonly isDarkMode: boolean;
5
4
  readonly isLightMode: boolean;
6
5
  /**
@@ -13,12 +12,14 @@ interface ThemePreference {
13
12
  * Read the user's OS-level color scheme preference
14
13
  * (`prefers-color-scheme`), and stay in sync as they change it.
15
14
  *
16
- * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
17
- * and does not tear. `theme` is `undefined` on the server — and on the client
18
- * until the first `matchMedia` read commits — render a neutral state for that
19
- * case rather than branching on `isDarkMode` / `isLightMode`, which are both
20
- * `false` until `theme` resolves (there are only two real themes, so "both
21
- * false" is unambiguous evidence that the preference isn't known yet).
15
+ * A thin specialization of {@link useMediaQuery} over
16
+ * `'(prefers-color-scheme: dark)'`, so it inherits that hook's
17
+ * `useSyncExternalStore` backing — safe under concurrent rendering, does not
18
+ * tear. `theme` is `undefined` on the server — and on the client until the
19
+ * first `matchMedia` read commits — render a neutral state for that case
20
+ * rather than branching on `isDarkMode` / `isLightMode`, which are both `false`
21
+ * until `theme` resolves (there are only two real themes, so "both false" is
22
+ * unambiguous evidence that the preference isn't known yet).
22
23
  *
23
24
  * @returns `theme` plus `isDarkMode` / `isLightMode` convenience booleans.
24
25
  * The returned object is memoized, so its identity only changes when `theme`
@@ -31,6 +32,4 @@ interface ThemePreference {
31
32
  * return <div data-theme={theme}>{isDarkMode ? '🌙' : '☀️'}</div>;
32
33
  * ```
33
34
  */
34
- declare function useTheme(): Readonly<ThemePreference>;
35
- //#endregion
36
- export { Theme, ThemePreference, useTheme };
35
+ export declare function useTheme(): Readonly<ThemePreference>;
@@ -1,25 +1,19 @@
1
- import { useMemo, useSyncExternalStore } from "react";
2
- //#region src/use-theme.ts
1
+ import { useMediaQuery } from "./use-media-query.mjs";
2
+ import { useMemo } from "react";
3
+ // src/use-theme.ts
3
4
  const QUERY = "(prefers-color-scheme: dark)";
4
- const getSnapshot = () => window.matchMedia(QUERY).matches ? "dark" : "light";
5
- const getServerSnapshot = () => void 0;
6
- const subscribe = (onStoreChange) => {
7
- const mediaQueryList = window.matchMedia(QUERY);
8
- mediaQueryList.addEventListener("change", onStoreChange);
9
- return () => {
10
- mediaQueryList.removeEventListener("change", onStoreChange);
11
- };
12
- };
13
5
  /**
14
6
  * Read the user's OS-level color scheme preference
15
7
  * (`prefers-color-scheme`), and stay in sync as they change it.
16
8
  *
17
- * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
18
- * and does not tear. `theme` is `undefined` on the server — and on the client
19
- * until the first `matchMedia` read commits — render a neutral state for that
20
- * case rather than branching on `isDarkMode` / `isLightMode`, which are both
21
- * `false` until `theme` resolves (there are only two real themes, so "both
22
- * false" is unambiguous evidence that the preference isn't known yet).
9
+ * A thin specialization of {@link useMediaQuery} over
10
+ * `'(prefers-color-scheme: dark)'`, so it inherits that hook's
11
+ * `useSyncExternalStore` backing — safe under concurrent rendering, does not
12
+ * tear. `theme` is `undefined` on the server — and on the client until the
13
+ * first `matchMedia` read commits — render a neutral state for that case
14
+ * rather than branching on `isDarkMode` / `isLightMode`, which are both `false`
15
+ * until `theme` resolves (there are only two real themes, so "both false" is
16
+ * unambiguous evidence that the preference isn't known yet).
23
17
  *
24
18
  * @returns `theme` plus `isDarkMode` / `isLightMode` convenience booleans.
25
19
  * The returned object is memoized, so its identity only changes when `theme`
@@ -33,12 +27,18 @@ const subscribe = (onStoreChange) => {
33
27
  * ```
34
28
  */
35
29
  function useTheme() {
36
- const theme = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
37
- return useMemo(() => ({
38
- theme,
39
- isDarkMode: theme === "dark",
40
- isLightMode: theme === "light"
41
- }), [theme]);
30
+ const isDark = useMediaQuery(QUERY);
31
+ return useMemo(() => {
32
+ if (isDark === void 0) return {
33
+ theme: void 0,
34
+ isDarkMode: false,
35
+ isLightMode: false
36
+ };
37
+ return {
38
+ theme: isDark ? "dark" : "light",
39
+ isDarkMode: isDark,
40
+ isLightMode: !isDark
41
+ };
42
+ }, [isDark]);
42
43
  }
43
- //#endregion
44
44
  export { useTheme };
@@ -1,5 +1,4 @@
1
- //#region src/use-window-size.d.ts
2
- interface WindowSize {
1
+ export interface WindowSize {
3
2
  /**
4
3
  * The viewport width in CSS pixels, or `undefined` before the client has
5
4
  * reported its actual size (always the case during SSR).
@@ -32,6 +31,4 @@ interface WindowSize {
32
31
  * return <div>{width} × {height}</div>;
33
32
  * ```
34
33
  */
35
- declare function useWindowSize(): Readonly<WindowSize>;
36
- //#endregion
37
- export { WindowSize, useWindowSize };
34
+ export declare function useWindowSize(): Readonly<WindowSize>;
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useRef, useSyncExternalStore } from "react";
2
- //#region src/use-window-size.ts
2
+ // src/use-window-size.ts
3
3
  const SERVER_SNAPSHOT = {
4
4
  width: void 0,
5
5
  height: void 0
@@ -48,5 +48,4 @@ function useWindowSize() {
48
48
  }, []);
49
49
  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
50
50
  }
51
- //#endregion
52
51
  export { useWindowSize };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodnight-dev/react-hooks",
3
- "version": "0.3.0",
3
+ "version": "0.5.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",
@@ -31,6 +31,14 @@
31
31
  "types": "./dist/use-local-storage.d.mts",
32
32
  "import": "./dist/use-local-storage.mjs"
33
33
  },
34
+ "./useMediaQuery": {
35
+ "types": "./dist/use-media-query.d.mts",
36
+ "import": "./dist/use-media-query.mjs"
37
+ },
38
+ "./useOnlineStatus": {
39
+ "types": "./dist/use-online-status.d.mts",
40
+ "import": "./dist/use-online-status.mjs"
41
+ },
34
42
  "./useTheme": {
35
43
  "types": "./dist/use-theme.d.mts",
36
44
  "import": "./dist/use-theme.mjs"
@@ -55,7 +63,7 @@
55
63
  },
56
64
  "devDependencies": {
57
65
  "@arethetypeswrong/cli": "^0.18.4",
58
- "@changesets/cli": "^2.31.0",
66
+ "@changesets/cli": "^3.0.0",
59
67
  "@commitlint/cli": "^21.2.0",
60
68
  "@commitlint/config-conventional": "^21.2.0",
61
69
  "@eslint/js": "^10.0.1",
@@ -71,13 +79,13 @@
71
79
  "eslint-plugin-perfectionist": "^5.9.1",
72
80
  "eslint-plugin-react-hooks": "^7.1.0",
73
81
  "globals": "^17.7.0",
74
- "jsdom": "^29.1.1",
82
+ "jsdom": "^31.0.0",
75
83
  "lefthook": "^2.1.9",
76
84
  "prettier": "^3.9.4",
77
85
  "publint": "^0.3.21",
78
86
  "react": "^19.2.0",
79
87
  "react-dom": "^19.2.0",
80
- "tsdown": "^0.22.3",
88
+ "tsdown": "^0.23.0",
81
89
  "typedoc": "^0.28.19",
82
90
  "typescript": "^6.0.3",
83
91
  "typescript-eslint": "^8.62.1",