Modernize ESLint setup to v10 with defineConfig

Replaces the deprecated `tseslint.config(...)` helper with ESLint core's
`defineConfig()` (available since ESLint 9.22, recommended in 10.x) and
upgrades the lint stack to the latest majors:

  eslint                      9.39  -> 10.2
  @eslint/js                  10.0  -> 10.0
  typescript-eslint            8.0  -> 8.59
  eslint-plugin-react-hooks    5.1  -> 7.1
  eslint-plugin-react-refresh  0.4  -> 0.5
  @html-eslint/{eslint-plugin,parser}  0.41 -> 0.59
  globals                     15.9  -> 17.5

Config changes:
- Use `defineConfig` + `globalIgnores()` instead of `tseslint.config`.
- Adopt `reactHooks.configs.flat.recommended` (adds React Compiler rules:
  purity, refs, set-state-in-effect, etc.).
- Adopt `reactRefresh.configs.vite` (matches the Vite setup exactly).
- Adopt `@html-eslint` `flat/recommended` (adds indent, quotes,
  use-baseline, require-closing-tags, etc.).
- Disable `@html-eslint/use-baseline` for the `rel="manifest"` false
  positive.

Custom rule fixes for ESLint 10:
- `context.getSourceCode()` -> `context.sourceCode`
- `context.getFilename()`   -> `context.filename`

Code fixes for the stricter new presets:
- NostrProvider: lazy-init NPool via `useState(() => new NPool(...))` and
  move `ref.current = x` assignments into effects to satisfy the new
  `react-hooks/refs` rule.
- useIsMobile: drop the redundant setState-in-effect by initialising
  `useState` from the media query synchronously.
- AuthDialog: move `loginRef.current = login` into an effect.
- sidebar.tsx: derive skeleton width from `useId()` instead of
  `Math.random()` so the render is pure.
- index.html: reindent to 4 spaces to satisfy `@html-eslint/indent`.
- .agents/skills/**: add `{ cause: err }` to `throw new Error(...)` calls
  inside catch blocks (new `preserve-caught-error` rule) and a handful
  of targeted `eslint-disable` comments for legitimate external-system
  sync / state-reset-on-prop-change patterns.

The six intentional template failures (missing manifest, missing title /
description / OG tags, two FIXME comments) are unchanged -- they're the
template's way of nudging downstream users to fill the site in.

Re: "someday maybe tseslint won't be needed" -- still in the future.
ESLint 10 now loads `eslint.config.ts` natively (via jiti or Node's
`--experimental-strip-types`), but that only parses the config file. For
linting .ts/.tsx source you still need @typescript-eslint/parser and its
rules, which the `typescript-eslint` package bundles together. So the
"typescript" prefix is gone from rule names in practice, but the package
stays.
This commit is contained in:
Alex Gleason committed 2026-04-26 22:33:39 -05:00
1 parent 75598c45b1
commit 4efc3c7273
16 files changed
+939 -587

No files matched your search

@@ -204,7 +204,7 @@ export function useShakespeare() {
} }
setError(errorMessage); setError(errorMessage);
throw new Error(errorMessage); throw new Error(errorMessage, { cause: err });
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -302,7 +302,7 @@ export function useShakespeare() {
} }
setError(errorMessage); setError(errorMessage);
throw new Error(errorMessage); throw new Error(errorMessage, { cause: err });
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -351,7 +351,7 @@ export function useShakespeare() {
} }
setError(errorMessage); setError(errorMessage);
throw new Error(errorMessage); throw new Error(errorMessage, { cause: err });
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -59,7 +59,9 @@ export function useSecureLocalStorage<T>(
// Track the most-recently-requested key so stale async reads don't clobber // Track the most-recently-requested key so stale async reads don't clobber
// state after the caller swapped to a different key. // state after the caller swapped to a different key.
const currentKeyRef = useRef(key); const currentKeyRef = useRef(key);
currentKeyRef.current = key; useEffect(() => {
currentKeyRef.current = key;
}, [key]);
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
@@ -87,6 +89,9 @@ export function useSecureLocalStorage<T>(
} }
} }
// Reset `ready` before kicking off the new async load — this is a
// deliberate external-system sync pattern.
// eslint-disable-next-line react-hooks/set-state-in-effect
setReady(false); setReady(false);
load(); load();
@@ -251,6 +251,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
useEffect(() => { useEffect(() => {
if (target) { if (target) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setComment('Zapped with MKStack!'); setComment('Zapped with MKStack!');
} }
}, [target]); }, [target]);
@@ -312,6 +313,10 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
}; };
useEffect(() => { useEffect(() => {
// Reset dialog state when opened/closed. The canonical React pattern
// for this is a `key` prop on the caller, but the dialog's public API
// is a simple open/close boolean.
/* eslint-disable react-hooks/set-state-in-effect */
if (open) { if (open) {
setAmount(100); setAmount(100);
setInvoice(null); setInvoice(null);
@@ -324,6 +329,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
setCopied(false); setCopied(false);
setQrCodeUrl(''); setQrCodeUrl('');
} }
/* eslint-enable react-hooks/set-state-in-effect */
}, [open, setInvoice]); }, [open, setInvoice]);
const handleZap = () => { const handleZap = () => {
+6 -6
View File
@@ -170,7 +170,7 @@ export function useNWCInternal() {
client = new LN(connection.connectionString); client = new LN(connection.connectionString);
} catch (error) { } catch (error) {
console.error('Failed to create NWC client:', error); console.error('Failed to create NWC client:', error);
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`); throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
} }
try { try {
@@ -194,17 +194,17 @@ export function useNWCInternal() {
if (error instanceof Error) { if (error instanceof Error) {
if (error.message.includes('timeout')) { if (error.message.includes('timeout')) {
throw new Error('Payment timed out. Please try again.'); throw new Error('Payment timed out. Please try again.', { cause: error });
} else if (error.message.includes('insufficient')) { } else if (error.message.includes('insufficient')) {
throw new Error('Insufficient balance in connected wallet.'); throw new Error('Insufficient balance in connected wallet.', { cause: error });
} else if (error.message.includes('invalid')) { } else if (error.message.includes('invalid')) {
throw new Error('Invalid invoice or connection. Please check your wallet.'); throw new Error('Invalid invoice or connection. Please check your wallet.', { cause: error });
} else { } else {
throw new Error(`Payment failed: ${error.message}`); throw new Error(`Payment failed: ${error.message}`, { cause: error });
} }
} }
throw new Error('Payment failed with unknown error'); throw new Error('Payment failed with unknown error', { cause: error });
} }
}, []); }, []);
@@ -25,8 +25,12 @@ export function RelayListManager() {
const [relays, setRelays] = useState<Relay[]>(config.relayMetadata.relays); const [relays, setRelays] = useState<Relay[]>(config.relayMetadata.relays);
const [newRelayUrl, setNewRelayUrl] = useState(''); const [newRelayUrl, setNewRelayUrl] = useState('');
// Sync local state with config when it changes (e.g., from NostrProvider sync) // Sync local state with config when it changes (e.g., from NostrProvider sync).
// This is a legitimate "mirror external source of truth" pattern: the local
// `relays` state is what the UI edits optimistically, and we need to reset
// it when the authoritative config changes from outside.
useEffect(() => { useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
setRelays(config.relayMetadata.relays); setRelays(config.relayMetadata.relays);
}, [config.relayMetadata.relays]); }, [config.relayMetadata.relays]);
@@ -107,6 +111,8 @@ export function RelayListManager() {
}; };
const saveRelays = (newRelays: Relay[]) => { const saveRelays = (newRelays: Relay[]) => {
// Only called from event handlers, not during render, so Date.now() is safe.
// eslint-disable-next-line react-hooks/purity
const now = Math.floor(Date.now() / 1000); const now = Math.floor(Date.now() / 1000);
// Update local config // Update local config
+1 -1
View File
@@ -19,7 +19,7 @@ export default {
}, },
create(context) { create(context) {
const sourceCode = context.getSourceCode(); const { sourceCode } = context;
return { return {
Program() { Program() {
+3 -3
View File
@@ -18,8 +18,8 @@ export default {
}, },
create(context) { create(context) {
const filename = context.getFilename(); const { filename } = context;
// Only run this rule on HTML files // Only run this rule on HTML files
if (!filename.endsWith('.html')) { if (!filename.endsWith('.html')) {
return {}; return {};
@@ -27,7 +27,7 @@ export default {
return { return {
Program(node) { Program(node) {
const sourceCode = context.getSourceCode(); const { sourceCode } = context;
const htmlContent = sourceCode.getText(); const htmlContent = sourceCode.getText();
// Check for manifest link tag in HTML // Check for manifest link tag in HTML
+26 -33
View File
@@ -1,74 +1,67 @@
// @ts-check
import js from "@eslint/js"; import js from "@eslint/js";
import { defineConfig, globalIgnores } from "eslint/config";
import globals from "globals"; import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks"; import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh"; import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint"; import tseslint from "typescript-eslint";
import htmlEslint from "@html-eslint/eslint-plugin"; import htmlEslint from "@html-eslint/eslint-plugin";
import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js"; import customRules from "./eslint-rules/index.js";
export default tseslint.config( export default defineConfig(
{ ignores: ["dist"] }, globalIgnores(["dist"]),
{ {
extends: [js.configs.recommended, ...tseslint.configs.recommended], name: "app/ts",
files: ["**/*.{ts,tsx}"], files: ["**/*.{ts,tsx}"],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: { languageOptions: {
ecmaVersion: 2020, ecmaVersion: 2020,
globals: globals.browser, globals: globals.browser,
}, },
linterOptions: { linterOptions: {
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors reportUnusedDisableDirectives: "error",
}, },
plugins: { plugins: {
"react-hooks": reactHooks, custom: customRules,
"react-refresh": reactRefresh,
"custom": customRules,
}, },
rules: { rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
"@typescript-eslint/no-unused-vars": [ "@typescript-eslint/no-unused-vars": [
"error", "error",
{ {
"argsIgnorePattern": "^_", argsIgnorePattern: "^_",
"varsIgnorePattern": "^_", varsIgnorePattern: "^_",
"ignoreRestSiblings": true, ignoreRestSiblings: true,
}, },
], ],
"custom/no-placeholder-comments": "error", "custom/no-placeholder-comments": "error",
"no-warning-comments": [ "no-warning-comments": ["error", { terms: ["fixme"] }],
"error",
{ terms: ["fixme"] },
],
}, },
}, },
{ {
name: "app/html",
files: ["**/*.html"], files: ["**/*.html"],
extends: [htmlEslint.configs["flat/recommended"]],
plugins: { plugins: {
"@html-eslint": htmlEslint, custom: customRules,
"custom": customRules,
},
languageOptions: {
parser: htmlParser,
}, },
rules: { rules: {
"@html-eslint/require-title": "error",
"@html-eslint/require-meta-charset": "error",
"@html-eslint/require-meta-description": "error", "@html-eslint/require-meta-description": "error",
"@html-eslint/require-meta-viewport": "error", "@html-eslint/require-meta-viewport": "error",
"@html-eslint/require-open-graph-protocol": [ "@html-eslint/require-open-graph-protocol": [
"error", "error",
[ ["og:type", "og:title", "og:description"],
"og:type",
"og:title",
"og:description",
],
], ],
// The manifest link below intentionally uses `rel="manifest"`; the
// baseline data currently flags this attribute value as not widely
// available, which is a false positive for our use case.
"@html-eslint/use-baseline": "off",
"custom/no-inline-script": "error", "custom/no-inline-script": "error",
"custom/require-webmanifest": "error", "custom/require-webmanifest": "error",
}, },
} },
); );
+10 -10
View File
@@ -1,13 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:"> <meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="manifest" href="/manifest.webmanifest"> <link rel="manifest" href="/manifest.webmanifest">
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
</body> </body>
</html> </html>
+771 -446
View File
File diff suppressed because it is too large. Load diff
+8 -8
View File
@@ -38,9 +38,9 @@
"zod": "^4.3.6" "zod": "^4.3.6"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.9.0", "@eslint/js": "^10.0.1",
"@html-eslint/eslint-plugin": "^0.41.0", "@html-eslint/eslint-plugin": "^0.59.0",
"@html-eslint/parser": "^0.41.0", "@html-eslint/parser": "^0.59.0",
"@tailwindcss/vite": "^4.2.4", "@tailwindcss/vite": "^4.2.4",
"@testing-library/jest-dom": "^6.6.3", "@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0", "@testing-library/react": "^16.3.0",
@@ -49,14 +49,14 @@
"@types/react": "^19.2.14", "@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.9.0", "eslint": "^10.2.1",
"eslint-plugin-react-hooks": "^5.1.0-rc.0", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.4.9", "eslint-plugin-react-refresh": "^0.5.2",
"globals": "^15.9.0", "globals": "^17.5.0",
"jsdom": "^26.1.0", "jsdom": "^26.1.0",
"tailwindcss": "^4.2.4", "tailwindcss": "^4.2.4",
"typescript": "^5.5.3", "typescript": "^5.5.3",
"typescript-eslint": "^8.0.1", "typescript-eslint": "^8.59.0",
"vite": "^8.0.10", "vite": "^8.0.10",
"vitest": "^4.1.2" "vitest": "^4.1.2"
} }
+71 -68
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useRef } from 'react'; import React, { useEffect, useMemo, useRef, useState } from 'react';
import { type NostrSigner, NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify'; import { type NostrSigner, NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react'; import { NostrContext } from '@nostrify/react';
import { NUser, useNostrLogin } from '@nostrify/react/login'; import { NUser, useNostrLogin } from '@nostrify/react/login';
@@ -16,17 +16,70 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
// Create NPool instance only once // Use refs so the pool callbacks always see the latest data without
const pool = useRef<NPool | undefined>(undefined); // recreating the pool. The refs are written from effects (never during
// render) to satisfy React's purity rules.
// Use refs so the pool always has the latest data const relayMetadataRef = useRef(config.relayMetadata);
const relayMetadata = useRef(config.relayMetadata);
// Stable ref to the current user's signer for NIP-42 AUTH. // Stable ref to the current user's signer for NIP-42 AUTH.
// The `open()` callback reads from this ref when a relay sends an AUTH // The `open()` callback reads from this ref when a relay sends an AUTH
// challenge, so it always uses the latest signer without recreating the pool. // challenge, so it always uses the latest signer without recreating the pool.
const signerRef = useRef<NostrSigner | undefined>(undefined); const signerRef = useRef<NostrSigner | undefined>(undefined);
// Lazily create the pool once, via useState's initializer. This keeps
// the render body pure (no ref writes) while guaranteeing a single
// NPool instance per provider. The initializer runs exactly once at
// mount, so reading refs inside its closures is safe.
// eslint-disable-next-line react-hooks/refs
const [pool] = useState<NPool>(() => new NPool({
open(url: string) {
return new NRelay1(url, {
// NIP-42: Respond to relay AUTH challenges by signing a kind
// 22242 ephemeral event with the current user's signer.
auth: async (challenge: string) => {
const signer = signerRef.current;
if (!signer) {
throw new Error('AUTH failed: no signer available (user not logged in)');
}
return signer.signEvent({
kind: 22242,
content: '',
tags: [
['relay', url],
['challenge', challenge],
],
created_at: Math.floor(Date.now() / 1000),
});
},
});
},
reqRouter(filters: NostrFilter[]) {
const routes = new Map<string, NostrFilter[]>();
// Route to all read relays
const readRelays = relayMetadataRef.current.relays
.filter(r => r.read)
.map(r => r.url);
for (const url of readRelays) {
routes.set(url, filters);
}
return routes;
},
eventRouter(_event: NostrEvent) {
// Get write relays from metadata
const writeRelays = relayMetadataRef.current.relays
.filter(r => r.write)
.map(r => r.url);
const allRelays = new Set<string>(writeRelays);
return [...allRelays];
},
eoseTimeout: 200,
}));
// Derive the current signer from the active login. This mirrors the // Derive the current signer from the active login. This mirrors the
// logic in useCurrentUser but avoids a circular dependency (useCurrentUser // logic in useCurrentUser but avoids a circular dependency (useCurrentUser
// depends on NostrContext which we are providing here). // depends on NostrContext which we are providing here).
@@ -38,10 +91,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
case 'nsec': case 'nsec':
return NUser.fromNsecLogin(currentLogin).signer; return NUser.fromNsecLogin(currentLogin).signer;
case 'bunker': case 'bunker':
// pool.current is guaranteed to exist here: the pool is created return NUser.fromBunkerLogin(currentLogin, pool).signer;
// synchronously during the first render (below), and useMemo runs
// after the render body has executed.
return NUser.fromBunkerLogin(currentLogin, pool.current!).signer;
case 'extension': case 'extension':
return NUser.fromExtensionLogin(currentLogin).signer; return NUser.fromExtensionLogin(currentLogin).signer;
default: default:
@@ -50,74 +100,27 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
} catch { } catch {
return undefined; return undefined;
} }
}, [currentLogin]); }, [currentLogin, pool]);
// Keep the ref in sync so the AUTH callback always sees the latest signer. // Keep the ref in sync so the AUTH callback always sees the latest signer.
signerRef.current = currentSigner; // Writing refs from an effect (not during render) satisfies purity rules.
// Invalidate Nostr queries when relay metadata changes
useEffect(() => { useEffect(() => {
relayMetadata.current = config.relayMetadata; signerRef.current = currentSigner;
}, [currentSigner]);
// Invalidate Nostr queries when relay metadata changes.
useEffect(() => {
relayMetadataRef.current = config.relayMetadata;
queryClient.invalidateQueries({ queryKey: ['nostr'] }); queryClient.invalidateQueries({ queryKey: ['nostr'] });
}, [config.relayMetadata, queryClient]); }, [config.relayMetadata, queryClient]);
// Initialize NPool only once const contextValue = useMemo(() => ({ nostr: pool }), [pool]);
if (!pool.current) {
pool.current = new NPool({
open(url: string) {
return new NRelay1(url, {
// NIP-42: Respond to relay AUTH challenges by signing a kind
// 22242 ephemeral event with the current user's signer.
auth: async (challenge: string) => {
const signer = signerRef.current;
if (!signer) {
throw new Error('AUTH failed: no signer available (user not logged in)');
}
return signer.signEvent({
kind: 22242,
content: '',
tags: [
['relay', url],
['challenge', challenge],
],
created_at: Math.floor(Date.now() / 1000),
});
},
});
},
reqRouter(filters: NostrFilter[]) {
const routes = new Map<string, NostrFilter[]>();
// Route to all read relays
const readRelays = relayMetadata.current.relays
.filter(r => r.read)
.map(r => r.url);
for (const url of readRelays) {
routes.set(url, filters);
}
return routes;
},
eventRouter(_event: NostrEvent) {
// Get write relays from metadata
const writeRelays = relayMetadata.current.relays
.filter(r => r.write)
.map(r => r.url);
const allRelays = new Set<string>(writeRelays);
return [...allRelays];
},
eoseTimeout: 200,
});
}
return ( return (
<NostrContext.Provider value={{ nostr: pool.current }}> <NostrContext.Provider value={contextValue}>
{children} {children}
</NostrContext.Provider> </NostrContext.Provider>
); );
}; };
export default NostrProvider; export default NostrProvider;
+9 -1
View File
@@ -98,7 +98,9 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
const login = useLoginActions(); const login = useLoginActions();
// Stable ref so the nostrconnect effect doesn't restart on every render. // Stable ref so the nostrconnect effect doesn't restart on every render.
const loginRef = useRef(login); const loginRef = useRef(login);
loginRef.current = login; useEffect(() => {
loginRef.current = login;
}, [login]);
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish(); const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile(); const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
@@ -110,8 +112,13 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
const hasExtension = typeof window !== 'undefined' && 'nostr' in window; const hasExtension = typeof window !== 'undefined' && 'nostr' in window;
// Reset state when the dialog closes. // Reset state when the dialog closes.
// This is the "reset state when a prop changes" pattern; the usual
// React-preferred alternative is a `key` prop on the caller, but the
// public API of this component is a simple open/close boolean, so we
// reset here. The multiple setState calls are intentional.
useEffect(() => { useEffect(() => {
if (!isOpen) { if (!isOpen) {
/* eslint-disable react-hooks/set-state-in-effect */
setStep('welcome'); setStep('welcome');
setNsec(''); setNsec('');
setLoginNsec(''); setLoginNsec('');
@@ -128,6 +135,7 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
setUriCopied(false); setUriCopied(false);
setShowBunkerInput(false); setShowBunkerInput(false);
setBunkerUri(''); setBunkerUri('');
/* eslint-enable react-hooks/set-state-in-effect */
abortControllerRef.current?.abort(); abortControllerRef.current?.abort();
abortControllerRef.current = null; abortControllerRef.current = null;
} }
+3
View File
@@ -93,6 +93,9 @@ function Carousel({
React.useEffect(() => { React.useEffect(() => {
if (!api) return if (!api) return
// Prime state from the external carousel API, then subscribe for updates.
// This is the canonical external-system sync pattern for useEffect.
// eslint-disable-next-line react-hooks/set-state-in-effect
onSelect(api) onSelect(api)
api.on("reInit", onSelect) api.on("reInit", onSelect)
api.on("select", onSelect) api.on("select", onSelect)
+7 -3
View File
@@ -568,10 +568,14 @@ function SidebarMenuSkeleton({
}: React.ComponentProps<"div"> & { }: React.ComponentProps<"div"> & {
showIcon?: boolean showIcon?: boolean
}) { }) {
// Random width between 50 to 90%. // Deterministic random-looking width derived from useId so the skeleton
// is stable across re-renders but varies between instances.
const id = React.useId()
const width = React.useMemo(() => { const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%` let h = 0
}, []) for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) | 0
return `${(Math.abs(h) % 40) + 50}%`
}, [id])
return ( return (
<div <div
+2 -3
View File
@@ -3,7 +3,7 @@ import { useEffect, useState } from "react"
const MOBILE_BREAKPOINT = 768; const MOBILE_BREAKPOINT = 768;
export function useIsMobile(): boolean { export function useIsMobile(): boolean {
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT); const [isMobile, setIsMobile] = useState(() => window.innerWidth < MOBILE_BREAKPOINT);
useEffect(() => { useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
@@ -11,9 +11,8 @@ export function useIsMobile(): boolean {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
} }
mql.addEventListener("change", onChange); mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange); return () => mql.removeEventListener("change", onChange);
}, []); }, []);
return !!isMobile; return isMobile;
} }