Skip to content
This repository was archived by the owner on Sep 16, 2026. It is now read-only.

fix(web): prevent React hydration errors #418 and #185 - #438

Merged
leoisadev1 merged 1 commit into
mainfrom
fix/react-hydration-errors-v2
Nov 27, 2025
Merged

leoisadev1 merged 1 commit into
mainfrom
fix/react-hydration-errors-v2

Conversation

@leoisadev1

Copy link
Copy Markdown
Member

Summary

Changes

  1. Fix virtualListContainerStyle useMemo in chat-messages-panel.tsx and app-sidebar.tsx

    • Use computed totalSize value as dependency instead of function call in dependency array
    • Prevents infinite re-renders from dependency array function calls during hydration
  2. Fix useChatReadStatus hydration mismatch

    • Use requestAnimationFrame to delay localStorage access until after hydration
    • Add hasMountedRef to ensure localStorage operations only happen client-side
    • Return stable empty values during SSR to match server render

Root Cause

  • The useMemo dependency arrays were calling virtualizer.getTotalSize() which evaluates during the dependency check, causing unstable dependencies
  • useChatReadStatus was accessing localStorage and Date.now() during initial client render, causing server/client mismatch

- Fix virtualListContainerStyle useMemo in chat-messages-panel.tsx and app-sidebar.tsx
  - Use computed totalSize value as dependency instead of function call
  - Prevents infinite re-renders from dependency array function calls

- Fix useChatReadStatus hydration mismatch
  - Use requestAnimationFrame to delay localStorage access until after hydration
  - Add hasMountedRef to ensure localStorage operations only happen client-side
  - Return stable empty values during SSR to match server render
@vercel

vercel Bot commented Nov 27, 2025 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
openchat-web Ready Ready Preview Comment Nov 27, 2025 11:30pm

@greptile-apps

greptile-apps Bot commented Nov 27, 2025

Copy link
Copy Markdown
Contributor

Greptile Overview

Greptile Summary

This PR fixes React hydration errors (#418) and maximum update depth issues (#185) by stabilizing dependency arrays and deferring client-side operations until after hydration.

Key Changes:

  • Fixed useMemo in app-sidebar.tsx and chat-messages-panel.tsx by extracting virtualizer.getTotalSize() call outside dependency array to prevent infinite re-renders
  • Added requestAnimationFrame delay in useChatReadStatus hook to defer localStorage access until after React hydration completes
  • Added hasMountedRef tracking to ensure client-side operations only run after mount

Issues Found:

  • Potential race condition in use-chat-read-status.ts where RAF callback could update state on unmounted component (Score: 3/5)
  • Misleading comment about "Skip if already loaded" when checking hasMountedRef instead of isLoaded (Score: 2/5)

Confidence Score: 4/5

  • This PR is safe to merge with minor issues that should be addressed
  • The core fixes are sound and address real hydration issues. However, there's a race condition where the RAF callback in use-chat-read-status.ts could update state on an unmounted component (score 3/5), and some misleading comments (score 1-2/5). These are minor issues that don't affect functionality in normal usage but should be cleaned up.
  • apps/web/src/hooks/use-chat-read-status.ts needs attention for the RAF callback race condition

Important Files Changed

File Analysis

Filename Score Overview
apps/web/src/components/app-sidebar.tsx 5/5 Fixed useMemo dependency from virtualizer object to totalSize value to prevent infinite re-renders
apps/web/src/components/chat-messages-panel.tsx 5/5 Fixed useMemo dependency from getTotalSize() call to totalSize value to prevent infinite re-renders
apps/web/src/hooks/use-chat-read-status.ts 4/5 Added requestAnimationFrame delay and hasMountedRef to fix hydration mismatch by deferring localStorage access

Sequence Diagram

sequenceDiagram
    participant Browser
    participant React
    participant Component
    participant Virtualizer
    participant LocalStorage
    
    Note over Browser,LocalStorage: Initial SSR/Hydration Phase
    
    React->>Component: Server render
    Component->>Component: Initialize with empty values
    Component->>React: Return SSR HTML
    
    Browser->>React: Load client bundle
    React->>Component: Hydrate (client render)
    
    Note over Component: useChatReadStatus hook
    Component->>Component: hasMountedRef = false
    Component->>Component: isLoaded = false
    Component->>React: Return empty values (matches SSR)
    
    React->>Component: useEffect runs
    Component->>Component: Set hasMountedRef = true
    Component->>Browser: requestAnimationFrame()
    
    Note over Browser,LocalStorage: After Hydration (RAF Callback)
    
    Browser->>Component: RAF callback executes
    Component->>LocalStorage: getItem(INIT_TIME_KEY)
    LocalStorage-->>Component: Return init time or null
    Component->>LocalStorage: getItem(STORAGE_KEY)
    LocalStorage-->>Component: Return read times
    Component->>Component: setReadTimes(parsed data)
    Component->>Component: setIsLoaded(true)
    
    Note over Component,Virtualizer: Virtualizer Fix
    
    Component->>Virtualizer: getTotalSize()
    Virtualizer-->>Component: Return size value
    Component->>Component: useMemo([totalSize])
    Note over Component: Stable dependency prevents<br/>infinite re-renders
    
    Note over Browser,Component: User Navigates to Chat
    
    Browser->>Component: Pathname changes
    Component->>Component: useEffect detects change
    Component->>Component: markAsRead(chatId)
    Component->>LocalStorage: setItem(STORAGE_KEY, updated times)
Loading

@greptile-apps greptile-apps 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.

3 files reviewed, 3 comments

Edit Code Review Agent Settings | Greptile

Comment on lines 33 to +36
useEffect(() => {
if (typeof window === "undefined") return;
// Skip if already loaded or during SSR
if (hasMountedRef.current) return;
hasMountedRef.current = true;

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.

style: The check on line 35 is redundant since hasMountedRef.current can only be true inside this useEffect after it's set on line 36.

The real issue: the dependency array is empty [], so this effect only runs once. But the guard if (hasMountedRef.current) return; on line 35 means the effect will ALWAYS execute its logic on first run (since hasMountedRef.current starts as false). The early return never triggers.

Suggested change
useEffect(() => {
if (typeof window === "undefined") return;
// Skip if already loaded or during SSR
if (hasMountedRef.current) return;
hasMountedRef.current = true;
useEffect(() => {
// Only run once on mount
if (hasMountedRef.current) return;
hasMountedRef.current = true;

Score: 2/5 - This is more of a code clarity issue than a bug, but the comment "Skip if already loaded" is misleading since we're checking hasMountedRef not isLoaded.

Comment on lines +40 to +69
const rafId = requestAnimationFrame(() => {
// Get or set the initialization time (when tracking first started)
let initTime = 0;
try {
const storedInitTime = localStorage.getItem(INIT_TIME_KEY);
if (storedInitTime) {
initTime = Number.parseInt(storedInitTime, 10);
} else {
// First time using this feature - set init time to now
// This means existing chats won't show as unread
initTime = Date.now();
localStorage.setItem(INIT_TIME_KEY, String(initTime));
}
} catch {
initTime = Date.now();
localStorage.setItem(INIT_TIME_KEY, String(initTime));
}
} catch {
initTime = Date.now();
}
initTimeRef.current = initTime;

// Load stored read times
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
setReadTimes(JSON.parse(stored));
initTimeRef.current = initTime;

// Load stored read times
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
const parsed = JSON.parse(stored);
setReadTimes(parsed);
}
} catch {
// Ignore parse errors
}
} catch {
// Ignore parse errors
}
setIsLoaded(true);
setIsLoaded(true);
});

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.

logic: Potential race condition: if the component unmounts quickly (before RAF callback fires), the RAF callback will still execute and call setReadTimes and setIsLoaded on an unmounted component.

The cleanup function cancelAnimationFrame(rafId) won't prevent this because rafId is only assigned AFTER requestAnimationFrame returns, but the function passed to requestAnimationFrame captures the initial undefined value.

Suggested change
const rafId = requestAnimationFrame(() => {
// Get or set the initialization time (when tracking first started)
let initTime = 0;
try {
const storedInitTime = localStorage.getItem(INIT_TIME_KEY);
if (storedInitTime) {
initTime = Number.parseInt(storedInitTime, 10);
} else {
// First time using this feature - set init time to now
// This means existing chats won't show as unread
initTime = Date.now();
localStorage.setItem(INIT_TIME_KEY, String(initTime));
}
} catch {
initTime = Date.now();
localStorage.setItem(INIT_TIME_KEY, String(initTime));
}
} catch {
initTime = Date.now();
}
initTimeRef.current = initTime;
// Load stored read times
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
setReadTimes(JSON.parse(stored));
initTimeRef.current = initTime;
// Load stored read times
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
const parsed = JSON.parse(stored);
setReadTimes(parsed);
}
} catch {
// Ignore parse errors
}
} catch {
// Ignore parse errors
}
setIsLoaded(true);
setIsLoaded(true);
});
const rafId = requestAnimationFrame(() => {
// Check if component is still mounted
if (!hasMountedRef.current) return;
// Get or set the initialization time (when tracking first started)

Add a check at the start of the RAF callback to ensure we don't update state after unmount.

Score: 3/5 - This could cause React warnings about setting state on unmounted components in fast navigation scenarios.

Comment on lines 75 to +77
const markAsRead = useCallback((chatId: string) => {
// Don't mark as read until we've loaded (prevents overwriting stored data)
if (!hasMountedRef.current) return;

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.

style: The comment "prevents overwriting stored data" is misleading - the guard prevents marking chats as read before the initial data is loaded.

Suggested change
const markAsRead = useCallback((chatId: string) => {
// Don't mark as read until we've loaded (prevents overwriting stored data)
if (!hasMountedRef.current) return;
// Don't mark as read until mounted and loaded (ensures we don't race with initial load)
if (!hasMountedRef.current) return;

Score: 1/5 - Minor comment clarity issue.

@leoisadev1
leoisadev1 merged commit 1fe4259 into main Nov 27, 2025
@leoisadev1
leoisadev1 deleted the fix/react-hydration-errors-v2 branch November 27, 2025 23:32

This branch was successfully deployed

1 active deployment
Preview — 9db4ed44 Deployed Nov 27, 2025 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant