Skip to content

Conversation

karthikeyamadhavan123
Copy link

@karthikeyamadhavan123 karthikeyamadhavan123 commented Sep 27, 2025

fix: prevent hydration error in ThemeToggle (Fixes #610)
Description

This PR resolves a React hydration mismatch error that occurs during initial page load when rendering the ThemeToggle component.

The issue occurred because the theme context (useTheme from next-themes) attempted to read from localStorage during the first render. Since localStorage is only available in the browser, the server-rendered HTML mismatched the client-rendered output, causing hydration errors.

Technical Solution

Implemented the “wait until mounted” pattern in ThemeToggle.tsx:

Added const [isClient, setIsClient] = useState(false).

Used useEffect to update setIsClient(true) after the component mounts.

Conditionally rendered the theme toggle button:

{isClient && ...}

Ensures the button and theme icons only render on the client, eliminating hydration errors.

Motivation and Context

Prevents hydration warnings/errors in the console.

Ensures a smoother user experience without flicker or mismatched UI.

Improves code clarity by explicitly separating SSR and client-only logic.

Screenshots

Before (hydration error present):
Screenshot 2025-09-27 190825

After (hydration fixed):
Screenshot 2025-09-27 190914

and there was bug in the responsiveness of navbar which was overflowing on 320px
which was fixed
Before
image
After
image

Type of Change

Bug fix (non-breaking change which fixes an issue)

Code refactoring

How Has This Been Tested?

Steps to Reproduce & Verify Fix:

Run bun run dev.

Open the app in browser.

Perform a hard refresh (Ctrl/Cmd + Shift + R).

✅ Verify that no hydration errors (Hydration failed / Expected server HTML…) appear in the console.

✅ Confirm that the theme toggle button appears and works (light ↔ dark mode).

Test Environment:

Node.js: [v22.14.0]

Browser: [Brave 1.8.12]

OS: [Windows]

Checklist

My code follows the project style guidelines

Self-reviewed my code

Added screenshots if UI has changed

Commented code where necessary

Updated documentation if needed

No new warnings introduced

Verified fix with manual console check

Existing tests pass locally

Summary by CodeRabbit

  • New Features

    • Theme toggle now dynamically displays Sun or Moon icons based on the current theme.
  • Bug Fixes

    • Prevents hydration mismatch by rendering the toggle only after the page mounts, reducing initial icon flicker.
  • Style

    • Header right-side spacing and centering updated for improved horizontal alignment.
  • Accessibility

    • Screen-reader label for the toggle preserved to maintain accessibility.

Uses the isClient state with useEffect to ensure the theme button is only rendered client-side, preventing the SSR/client mismatch when reading user preferences from localStorage.
@netlify
Copy link

netlify bot commented Sep 27, 2025

👷 Deploy request for appcut pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 5720a4e

@vercel
Copy link

vercel bot commented Sep 27, 2025

@karthikeyamadhavan123 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 Sep 27, 2025

Walkthrough

Adds a client-side hydration guard to the theme toggle to avoid SSR/CSR mismatches; the Button is rendered only after mount and shows Sun or Moon based on current theme. Header rightContent classes were adjusted to change spacing/centering. No public API changes.

Changes

Cohort / File(s) Summary
Theme toggle component
apps/web/src/components/theme-toggle.tsx
Added isClient state with useEffect to defer rendering until mounted; Button now renders conditionally and shows Sun or Moon icon depending on theme; added useState/useEffect imports; preserved the screen-reader span inside the button.
Header layout classes
apps/web/src/components/header.tsx
Updated layout class names for rightContent: changed gap/centering classes (from gap-2/gap-4 to gap-1/gap-3 with centered layout). No structural or content changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant Browser as Browser
  participant SSR as Server (SSR)
  participant TT as ThemeToggle (Client)
  participant Theme as Theme Store

  Note over SSR,Browser: Server renders initial HTML without client-only button
  Browser->>TT: Load & hydrate
  TT->>TT: useEffect -> set isClient = true
  TT->>Theme: read current theme (dark/light)
  TT-->>Browser: render Button with Sun (if dark) or Moon (if light)

  U->>TT: click toggle
  TT->>Theme: toggle theme
  Theme-->>TT: updated theme
  TT-->>Browser: re-render with updated icon
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I flip the sky from dusk to dawn,
With moon and sun I hop along.
I wait to mount, then show my light,
No mismatched hum in dev's night.
A tiny toggle, calm and bright. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The style updates to the Header component’s layout classes in apps/web/src/components/header.tsx are unrelated to the hydration error fix and fall outside the objectives defined in issue #610. Please remove or relocate the Header styling adjustments into a separate pull request so that this change set focuses solely on resolving the ThemeToggle hydration issue.
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 title “Fix/toggle theme hydration error” succinctly identifies the main change of resolving the hydration mismatch in the ThemeToggle component by delaying client-side rendering until after mount.
Linked Issues Check ✅ Passed The changes in ThemeToggle.tsx directly implement the “wait until mounted” pattern described in issue #610 by using an isClient state guard, conditional rendering of the toggle button, and dynamic Sun/Moon icon swapping, which eliminates the SSR/client mismatch and prevents hydration errors as intended.
Description Check ✅ Passed The pull request description provides a concise summary of the changes and explicitly references the related issue (#610) using “Fixes #610,” it details the technical solution and motivation, includes before/after screenshots, outlines testing steps with environment details, and presents a project checklist, thereby covering all core sections specified by the repository template.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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
🧪 Early access (Sonnet 4.5): enabled

We are currently testing the Sonnet 4.5 model, which is expected to improve code review quality. However, this model may lead to increased noise levels in the review comments. Please disable the early access features if the noise level causes any inconvenience.

Note:

  • Public repositories are always opted into early access features.
  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.

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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a346bdf and e7f4883.

📒 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

@AANDDARK
Copy link

Thanks this it is fix my problem too #618

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

2 participants