Skip to content

Conversation

@sagarkawad
Copy link

@sagarkawad sagarkawad commented Oct 18, 2025

Description

fixed the hydration error while toggling between light and dark theme by using a state variable isMounted and setting it to true only when the component has been mounted in the client side

Fixes #610 (issue)

Type of change

  • [✅] Bug fix (non-breaking change which fixes an issue)

How Has This Been Tested?

I actually ran the application locally to verify the changes. You can test the application's homepage to see error free rendering.

Test Configuration:

  • Node version: v22.16.0
  • Browser (if applicable): Brave Browser
  • Operating System: MacOS

Screenshots (if applicable)

Screenshot 2025-10-18 at 10 13 00 AM Screenshot 2025-10-18 at 10 13 10 AM

Checklist:

  • [✅] My code follows the style guidelines of this project
  • [✅] I have performed a self-review of my code
  • [✅] I have added screenshots if ui has been changed
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • [✅] My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • [✅] New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced theme toggle reliability by resolving server-side rendering and client-side synchronization issues, ensuring consistent functionality across page loads.

@netlify
Copy link

netlify bot commented Oct 18, 2025

👷 Deploy request for appcut pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 08bd20c

@vercel
Copy link

vercel bot commented Oct 18, 2025

@sagarkawad is attempting to deploy a commit to the OpenCut OSS Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 18, 2025

Walkthrough

The theme-toggle component is modified to prevent hydration mismatches by introducing a mounted state flag. During initial server-client render, a disabled placeholder button is rendered; after hydration completes, the interactive theme toggle is displayed.

Changes

Cohort / File(s) Summary
Hydration State Management
apps/web/src/components/theme-toggle.tsx
Adds useState and useEffect hooks to track component hydration. Implements conditional rendering: disabled placeholder button before mount, interactive theme toggle after mount to prevent server-client render mismatch.

Sequence Diagram

sequenceDiagram
    participant SSR as Server-Side Render
    participant Client
    participant DOM
    
    SSR->>DOM: Render disabled theme button (placeholder)
    Client->>Client: Hydrate page
    Client->>DOM: mounted = false, render disabled button
    Client->>Client: useEffect triggers, mounted = true
    Client->>DOM: Re-render interactive theme toggle
    Client->>DOM: Attach event listeners
    Note over DOM: Component interactive, no hydration error
Loading

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

Poem

🐰 A toggle was broken, themes didn't align,
Server said "dark" but the client said "light"—
With a mounted state flag, hydration feels fine,
Now client and server agree, day and night! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The PR title "fix: Hydration error when switching between Dark/Light theme" directly and clearly describes the main change in the changeset. The title accurately captures the primary objective of fixing a hydration mismatch error that occurs when toggling between dark and light themes. It is concise, specific, and follows a clear conventional format that would help teammates quickly understand the purpose of this change when scanning the pull request history.
Linked Issues Check ✅ Passed The code changes directly address the requirements outlined in issue #610. The issue identified a hydration mismatch where the server rendered "Dark" by default while the client re-rendered "Light", causing a console warning. The implementation introduces a mounted state variable that acts as a client-side guard, rendering a disabled button placeholder on initial render and switching to the interactive theme toggle only after the component mounts. This approach ensures consistent rendering between server and client, which is the core requirement specified in the linked issue.
Out of Scope Changes Check ✅ Passed All changes in this PR are directly scoped to fixing the hydration error identified in issue #610. The modifications are confined to the theme-toggle.tsx component file and include only the necessary changes: adding React hooks, implementing a mounted state for tracking hydration completion, and adding a client-side mount guard. There are no unrelated refactorings, feature additions, or changes to other parts of the codebase that would fall outside the stated objective of resolving the hydration mismatch.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/components/theme-toggle.tsx (1)

34-34: Fix theme toggle to handle "system" theme value.

The app uses "system" as a valid theme (see sonner.tsx), but the toggle logic only handles "dark" and "light". When theme is "system", the condition theme === "dark" evaluates to false, causing it to set theme to "light" instead of properly cycling through values. The accessibility text at line 37 also needs updating to reflect the "system" state.

Lines to fix:

  • Line 34: Toggle logic to handle all three theme values ("dark", "light", "system")
  • Line 37: Accessibility text to display correct state for "system" theme
🧹 Nitpick comments (2)
apps/web/src/components/theme-toggle.tsx (2)

4-4: Remove unused Moon import or use it to toggle the icon.

The Moon icon is imported but never used. Either remove this import, or use it to toggle between Sun and Moon icons based on the current theme (see comment on lines 29-39).


29-39: Consider toggling the icon to match the screen reader text.

The screen reader text changes based on theme (line 37), but the icon always shows Sun (line 36). This creates an inconsistency between the visual and screen reader experience.

Consider conditionally rendering Sun or Moon based on the current theme to match the accessible text behavior.

-      <Sun className="!size-[1.1rem]" />
+      {theme === "dark" ? <Sun className="!size-[1.1rem]" /> : <Moon className="!size-[1.1rem]" />}
       <span className="sr-only">{theme === "dark" ? "Light" : "Dark"}</span>
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bee7aba and 08bd20c.

📒 Files selected for processing (1)
  • apps/web/src/components/theme-toggle.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{jsx,tsx}: Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Don't use distracting elements like <marquee> or <blink>.
Only use the scope prop on <th> elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Use semantic elements instead of role attributes in JSX.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with...

Files:

  • apps/web/src/components/theme-toggle.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use TypeScript namespaces.
Don't use non-null assertions with the ! postfix operator.
Don't use parameter properties in class constructors.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use either T[] or Array<T> consistently.
Initialize each enum member value explicitly.
Use export type for types.
Use import type for types.
Make sure all enum members are literal values.
Don't use TypeScript const enum.
Don't declare empty interfaces.
Don't let variables evolve into any type through reassignments.
Don't use the any type.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use implicit any type on variable declarations.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use the TypeScript directive @ts-ignore.
Use consistent accessibility modifiers on class properties and methods.
Use function types instead of object types with call signatures.
Don't use void type outside of generic or return types.

**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
Use either T[] or Array consistently
Don't use the any type

Files:

  • apps/web/src/components/theme-toggle.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,jsx,ts,tsx}: Don't use the return value of React.render.
Don't use consecutive spaces in regular expression literals.
Don't use the arguments object.
Don't use primitive type aliases or misleading types.
Don't use the comma operator.
Don't write functions that exceed a given Cognitive Complexity score.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names that aren't base 10 or use underscore separators.
Remove redundant terms from logical expressions.
Use while loops instead of...

Files:

  • apps/web/src/components/theme-toggle.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{tsx,jsx}: Always include a title element for icons unless there's text beside the icon
Always include a type attribute for button elements
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress
Accompany onMouseOver/onMouseOut with onFocus/onBlur
Don't import React itself
Don't define React components inside other components
Don't use both children and dangerouslySetInnerHTML on the same element
Don't insert comments as text nodes
Use <>...</> instead of ...

Files:

  • apps/web/src/components/theme-toggle.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{ts,tsx,js,jsx}: Don't use the comma operator
Use for...of statements instead of Array.forEach
Don't initialize variables to undefined
Use .flatMap() instead of map().flat() when possible
Don't assign a value to itself
Avoid unused imports and variables
Don't use await inside loops
Don't hardcode sensitive data like API keys and tokens
Don't use the delete operator
Don't use global eval()
Use String.slice() instead of String.substr() and String.substring()
Don't use else blocks when the if block breaks early
Put default function parameters and optional function parameters last
Use new when throwing an error
Use String.trimStart() and String.trimEnd() over String.trimLeft() and String.trimRight()

Files:

  • apps/web/src/components/theme-toggle.tsx
🧬 Code graph analysis (1)
apps/web/src/components/theme-toggle.tsx (1)
apps/web/src/app/layout.tsx (1)
  • RootLayout (22-55)
🔇 Additional comments (2)
apps/web/src/components/theme-toggle.tsx (2)

6-6: LGTM! Correct hydration fix pattern.

The mounted state with useEffect is the standard solution for preventing hydration mismatches with next-themes. This ensures the server and initial client render are identical, then switches to the interactive version after hydration completes.

Also applies to: 14-18


20-27: Placeholder button approach is correct.

Rendering a disabled placeholder during initial mount correctly prevents hydration mismatches. The button is properly disabled and includes screen reader text for accessibility.

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.

[BUG] Hydration error when switching between Dark/Light theme

1 participant