Skip to content

fix : preserve dark theme on locale switch and fix React 19 script wa… - #99

Merged
DataDave-Dev merged 1 commit into
DataDave-Dev:mainfrom
YasserYG8:fix/theme-persistence-i18n
Jun 17, 2026
Merged

DataDave-Dev merged 1 commit into
DataDave-Dev:mainfrom
YasserYG8:fix/theme-persistence-i18n

Conversation

@YasserYG8

@YasserYG8 YasserYG8 commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request: Fix Theme Reset on Locale Switch & React 19 Layout Warning

Description

This PR resolves Issue #95 ("Theme preference resets to light when switching language").

It addresses the issue of theme state loss during client-side route transitions (when changing the locale dynamic path parameter [lang]) and fixes the React 19 raw script tag console warning thrown during client navigation.


Key Changes

1. Theme Persistence on Locale Transitions (src/lib/use-theme.ts)

  • Added a usePathname-linked useEffect in the useIsDark theme state tracker hook.
  • When the user transitions between language paths (e.g., from /en to /es), the effect reads their theme choice (localStorage.theme) or system default and restores the "dark" class to document.documentElement, preventing React's router reconciler from resetting the layout back to light mode.

2. React 19 Script Tag Warning Resolution (src/app/[lang]/layout.tsx)

  • Implemented the type-toggle script pattern on the inline anti-FOUC (Flash of Unstyled Content) script in the root layout:
    type={typeof window === "undefined" ? "text/javascript" : "text/plain"}
  • During SSR: The script renders as text/javascript and runs synchronously before page load to apply the theme instantly.
  • During Hydration/Transitions: The script renders as text/plain, meaning React 19 recognizes it as plain text rather than an active script, eliminating the console warning when switching languages.

Verification & Testing Results

  • Unit Tests: pnpm test completed successfully with all 43/43 tests passing.
  • Production Build: pnpm build finished with zero errors, verifying correct compilation for all static locale pages under Next.js 16/Turbopack.

Summary by CodeRabbit

  • Bug Fixes
    • Improved dark mode theme handling to ensure the user's color preference persists correctly when navigating between pages.

@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The useIsDark hook gains a useEffect that re-applies the dark class on <html> on every route change, reading localStorage.theme or prefers-color-scheme. The layout's inline script now uses a conditional type attribute ("text/javascript" on SSR, "text/plain" on the client) to prevent double execution and suppress hydration warnings.

Changes

Dark Mode Route Awareness and Hydration Fix

Layer / File(s) Summary
Route-aware dark class initialization in useIsDark
src/lib/use-theme.ts
Adds useEffect and usePathname imports; introduces an effect that toggles the dark class on <html> from localStorage.theme or prefers-color-scheme: dark, re-running on each pathname change with try/catch error logging.
Conditional script type for SSR/client hydration
src/app/[lang]/layout.tsx
Changes the inline <script> type to "text/javascript" during SSR and "text/plain" on the client to avoid double execution and hydration mismatches.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 Hopping down each route I go,
The dark class follows, high or low.
Server says "run!" but client says "plain,"
No hydration mismatch, no React pain.
localStorage checked with a careful ear —
Every pathname change, the theme is clear! 🌙

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is comprehensive and covers the key changes, but does not follow the required template structure with the specified sections ('Qué hace', 'Tipo', 'Checklist'). Restructure the description to match the required template: add a brief 'Qué hace' section, select a 'Tipo' checkbox (should be 'fix'), and complete the 'Checklist' verifying lint, typecheck, test, and build pass.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the two main changes: preserving dark theme on locale switch and fixing a React 19 script warning in the layout.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/app/`[lang]/layout.tsx:
- Around line 40-41: The conditional logic for the script `type` attribute in
the layout.tsx Server Component evaluates only on the server during rendering,
so the `typeof window === "undefined"` check never switches to `text/plain` on
the client as intended. To fix this, convert the layout.tsx component to a
Client Component by adding the `use client` directive at the top of the file,
which will cause the script `type` attribute conditional to re-evaluate on the
client side where the window object is available and the type can properly
switch between `text/javascript` and `text/plain` for the React 19 hydration
warning mitigation.

In `@src/lib/use-theme.ts`:
- Around line 21-28: The theme resolution logic in the try block does not
properly handle storage failures. When localStorage.getItem("theme") throws an
error in restricted storage contexts, the entire theme determination is skipped,
including the matchMedia fallback. Restructure the logic by wrapping the
localStorage.getItem call in its own try-catch, and ensure that when
localStorage access fails, the code still falls back to using
window.matchMedia("(prefers-color-scheme: dark)").matches to determine the
theme. This way the document.documentElement.classList.toggle("dark", d) call
will always execute with a valid theme decision regardless of whether storage is
accessible.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 9782d1d9-ba82-4b4b-a2cc-1c07ff423177

📥 Commits

Reviewing files that changed from the base of the PR and between 5d827c2 and 682975c.

📒 Files selected for processing (2)
  • src/app/[lang]/layout.tsx
  • src/lib/use-theme.ts

Comment thread src/app/[lang]/layout.tsx
Comment on lines +40 to +41
type={typeof window === "undefined" ? "text/javascript" : "text/plain"}
suppressHydrationWarning

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

In Next.js App Router (v16), are app/**/layout.tsxfiles Server Components by default, and doestypeof window in those files evaluate server-side only (making it unsuitable for client-only script-type toggling)?

💡 Result:

In Next.js 16, app/layout.tsx files (and all other components within the app directory) are React Server Components by default [1][2][3]. Because they are Server Components, they execute on the server during the initial request [1][2][4]. Regarding your question about typeof window: 1. Server-Side Evaluation: When a layout.tsx file is a Server Component, code within the top-level scope (including typeof window checks) runs on the server [2][5]. Consequently, typeof window will evaluate to "undefined" on the server [5][6]. 2. Suitability for Client-Only Script Toggling: Using typeof window inside a Server Component layout is not a recommended or reliable way to perform client-side script toggling [7]. Because Server Components must remain deterministic during server-side rendering, attempting to conditionally render content based on the environment using typeof window can lead to hydration mismatches, where the server-rendered HTML does not match the client-side initial render [7]. Best Practice: If you need to execute code only in the browser or toggle UI based on client-side availability, you should: - Move that logic into a separate Client Component (marked with the 'use client' directive) [2][8]. - Utilize React hooks like useEffect, which only run on the client after hydration, to handle browser-specific APIs or script toggling [7]. - Alternatively, if you must keep the layout as a Server Component, you can import a Client Component to manage the client-side interactivity, ensuring that the environment-specific logic is encapsulated where it can safely access browser globals [8].

Citations:


type does not actually switch to text/plain because the decision is made server-side.

Since layout.tsx is a Server Component by default in Next.js App Router, the typeof window === "undefined" expression evaluates on the server, not the client. This means the script type attribute is set once during server rendering and remains fixed in the emitted HTML—the client never re-evaluates this condition. The React 19 warning/double-execution mitigation described in the PR is therefore not achieved.

🧰 Tools
🪛 ast-grep (0.43.0)

[warning] 41-41: Usage of dangerouslySetInnerHTML detected. This bypasses React's built-in XSS protection. Always sanitize HTML content using libraries like DOMPurify before injecting it into the DOM to prevent XSS attacks.
Context: dangerouslySetInnerHTML
Note: [CWE-79] Improper Neutralization of Input During Web Page Generation

(react-unsafe-html-injection)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/app/`[lang]/layout.tsx around lines 40 - 41, The conditional logic for
the script `type` attribute in the layout.tsx Server Component evaluates only on
the server during rendering, so the `typeof window === "undefined"` check never
switches to `text/plain` on the client as intended. To fix this, convert the
layout.tsx component to a Client Component by adding the `use client` directive
at the top of the file, which will cause the script `type` attribute conditional
to re-evaluate on the client side where the window object is available and the
type can properly switch between `text/javascript` and `text/plain` for the
React 19 hydration warning mitigation.

Comment thread src/lib/use-theme.ts
Comment on lines +21 to +28
const theme = localStorage.getItem("theme");
const d = theme
? theme === "dark"
: window.matchMedia("(prefers-color-scheme: dark)").matches;
document.documentElement.classList.toggle("dark", d);
} catch (e) {
console.error(e);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Harden theme resolution so fallback still works when storage access fails.

Right now, a storage error skips the matchMedia fallback entirely, and any non-empty unexpected value is forced to light. This can leave the route-transition fix ineffective in restricted storage contexts.

Suggested patch
   useEffect(() => {
-    try {
-      const theme = localStorage.getItem("theme");
-      const d = theme
-        ? theme === "dark"
-        : window.matchMedia("(prefers-color-scheme: dark)").matches;
-      document.documentElement.classList.toggle("dark", d);
-    } catch (e) {
-      console.error(e);
-    }
+    let d = window.matchMedia("(prefers-color-scheme: dark)").matches;
+    try {
+      const theme = localStorage.getItem("theme");
+      if (theme === "dark") d = true;
+      else if (theme === "light") d = false;
+    } catch (e) {
+      console.error(e);
+    }
+    document.documentElement.classList.toggle("dark", d);
   }, [pathname]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const theme = localStorage.getItem("theme");
const d = theme
? theme === "dark"
: window.matchMedia("(prefers-color-scheme: dark)").matches;
document.documentElement.classList.toggle("dark", d);
} catch (e) {
console.error(e);
}
useEffect(() => {
let d = window.matchMedia("(prefers-color-scheme: dark)").matches;
try {
const theme = localStorage.getItem("theme");
if (theme === "dark") d = true;
else if (theme === "light") d = false;
} catch (e) {
console.error(e);
}
document.documentElement.classList.toggle("dark", d);
}, [pathname]);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/use-theme.ts` around lines 21 - 28, The theme resolution logic in the
try block does not properly handle storage failures. When
localStorage.getItem("theme") throws an error in restricted storage contexts,
the entire theme determination is skipped, including the matchMedia fallback.
Restructure the logic by wrapping the localStorage.getItem call in its own
try-catch, and ensure that when localStorage access fails, the code still falls
back to using window.matchMedia("(prefers-color-scheme: dark)").matches to
determine the theme. This way the
document.documentElement.classList.toggle("dark", d) call will always execute
with a valid theme decision regardless of whether storage is accessible.

@DataDave-Dev
DataDave-Dev merged commit a22f52b into DataDave-Dev:main Jun 17, 2026
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants