Skip to content

Comments

performance#1663

Merged
MrgSub merged 1 commit intostagingfrom
07-07-performance
Jul 7, 2025
Merged

performance#1663
MrgSub merged 1 commit intostagingfrom
07-07-performance

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Jul 7, 2025

Performance Optimization for Mail List Component

Description

This PR optimizes the mail list component to improve rendering performance and reduce unnecessary re-renders. Key improvements include:

  1. Memoized the thread content rendering with useMemo to prevent unnecessary re-renders
  2. Removed unused code including prefetching logic and unused state variables
  3. Consolidated state calculations into a single useMemo hook for better organization
  4. Optimized the virtual list configuration with appropriate overscan and itemSize values
  5. Refactored the useThread hook to use memoization for derived values

Type of Change

  • ⚡ Performance improvement

Areas Affected

  • User Interface/Experience

Testing Done

  • Manual testing performed

Checklist

  • I have performed a self-review of my code
  • My changes generate no new warnings
  • All tests pass locally

Additional Notes

The virtual list configuration has been adjusted to use a fixed item size of 100px and reduced the overscan from 20 to 5 items, which should significantly improve scrolling performance. The trigger for loading more items has been adjusted to start when within 7 items of the end (previously 5).

Summary by CodeRabbit

  • Refactor
    • Improved performance and simplified state management in mail threads and mail list.
    • Optimized memoization for display flags, labels, and content rendering.
    • Consolidated selection state logic for mails.
    • Adjusted virtual list rendering for smoother scrolling and reduced resource usage.
    • Cleaned up unused code and removed outdated prefetching and theme logic.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 7, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes refactor the Thread and MailList components in the mail app by removing unused state, prefetching, and theme logic. Memoization is consolidated and optimized, and virtual list rendering parameters are adjusted. The useThread hook is also simplified by consolidating memoized computations and removing unused code.

Changes

File(s) Change Summary
apps/mail/components/mail/mail-list.tsx Removed unused state setters, prefetching, and theme code. Consolidated memoization for display flags and selection. Adjusted virtual list props (overscan, itemSize), and increased scroll loading threshold. Removed commented-out blocks.
apps/mail/hooks/use-threads.ts Removed unused imports and commented code. Consolidated memoization for draft, group thread, and thread data. Simplified hook return value and removed theme/image logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MailList
    participant Thread
    participant useThread

    User->>MailList: Scrolls or interacts
    MailList->>Thread: Renders thread item
    Thread->>useThread: Retrieves thread data (memoized)
    useThread-->>Thread: Returns latestDraft, isGroupThread, finalData
    Thread->>Thread: Computes display flags, labels, and emailContent (memoized)
    Thread-->>MailList: Renders memoized content
Loading

Possibly related PRs

  • mail-list performance #1631: Refactors and optimizes memoization and state management in mail-list.tsx, directly modifying the same component logic and hooks.
  • IFrame Performance Improv #1256: Adds email template prefetching logic to mail-list.tsx, which this PR removes, indicating overlapping but opposite changes.
  • No prefetch #1628: Removes or comments out email content prefetching and theme code in useThread, directly related to this PR's refactoring of the same hook.

Poem

In the mailbox, threads unwind,
Memoized thoughts now intertwined.
Prefetching gone, the code is neat,
With virtual lists that can’t be beat.
Rabbits hop and scroll with glee—
Simpler state, more memory free!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e8dd809 and 97ef1f9.

📒 Files selected for processing (2)
  • apps/mail/components/mail/mail-list.tsx (5 hunks)
  • apps/mail/hooks/use-threads.ts (2 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Collaborator Author

MrgSub commented Jul 7, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

@MrgSub MrgSub marked this pull request as ready for review July 7, 2025 19:47
Copy link
Collaborator Author

MrgSub commented Jul 7, 2025

Merge activity

  • Jul 7, 7:47 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jul 7, 7:47 PM UTC: @MrgSub merged this pull request with Graphite.

Copy link
Collaborator Author

MrgSub commented Jul 7, 2025

bugbot run

@MrgSub MrgSub merged commit 0ba8c97 into staging Jul 7, 2025
5 of 6 checks passed
@MrgSub MrgSub deleted the 07-07-performance branch July 7, 2025 19:47
Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

Performance optimization of mail component rendering and thread management through code cleanup and memoization improvements.

  • Optimized apps/mail/hooks/use-threads.ts by consolidating multiple useMemo hooks into a single computation for latestDraft, isGroupThread, and finalData
  • Enhanced apps/mail/components/mail/mail-list.tsx performance by removing template prefetching and optimizing VList configuration
  • Streamlined state management by removing unused dependencies (queryClient, settingsData) and dead code
  • Improved rendering efficiency through better memoization patterns and props organization

2 files reviewed, 2 comments
Edit PR Review Bot Settings | Greptile

Comment on lines 65 to 67
const [_threadId] = useQueryState('threadId');
const id = threadId ? threadId : _threadId;
const trpc = useTRPC();
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Optional chaining would be safer here. Consider: const id = threadId ?? _threadId

Comment on lines +93 to +102
const isGroupThread = threadQuery.data.latest?.id
? (() => {
const totalRecipients = [
...(threadQuery.data.latest.to || []),
...(threadQuery.data.latest.cc || []),
...(threadQuery.data.latest.bcc || []),
].length;
return totalRecipients > 1;
})()
: false;
Copy link
Contributor

Choose a reason for hiding this comment

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

style: IIFE not needed here. Can be simplified to a direct calculation

cursor[bot]

This comment was marked as outdated.

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Bug: Thread Data Refresh Issue

The removal of the useEffect that invalidated the thread query on historyId changes prevents thread data from refreshing. This causes stale or outdated thread content to be displayed when new messages or updates occur.

apps/mail/hooks/use-threads.ts#L62-L79

export const useThread = (threadId: string | null, historyId?: string | null) => {
const { data: session } = useSession();
const [_threadId] = useQueryState('threadId');
const id = threadId ? threadId : _threadId;
const trpc = useTRPC();
const threadQuery = useQuery(
trpc.mail.get.queryOptions(
{
id: id!,
},
{
enabled: !!id && !!session?.user.id,
staleTime: 1000 * 60 * 60, // 60 minutes
},
),
);

Fix in CursorFix in Web


Bug: Incomplete Dependencies Cause Stale UI and Callback Issues

The content useMemo hook's dependency array is incomplete, missing handleToggleStar, handleToggleImportant, moveThreadTo, setMail, displayStarred, displayImportant, and hasDraft. This leads to stale UI (e.g., incorrect star/important states, missing draft indicator) and outdated callback references, causing incorrect user interactions.

apps/mail/components/mail/mail-list.tsx#L232-L565

const content = useMemo(() => {
if (!latestMessage || !getThreadData) return null;
return (
<div
className={cn('select-none border-b md:my-1 md:border-none')}
onClick={onClick ? onClick(latestMessage) : undefined}
onMouseEnter={() => {
window.dispatchEvent(new CustomEvent('emailHover', { detail: { id: idToUse } }));
}}
onMouseLeave={() => {
window.dispatchEvent(new CustomEvent('emailHover', { detail: { id: null } }));
}}
>
<div
data-thread-id={idToUse}
key={idToUse}
className={cn(
'hover:bg-offsetLight hover:bg-primary/5 group relative mx-1 flex cursor-pointer flex-col items-start rounded-lg py-2 text-left text-sm transition-all hover:opacity-100',
(isMailSelected || isMailBulkSelected || isKeyboardFocused) &&
'border-border bg-primary/5 opacity-100',
isKeyboardFocused && 'ring-primary/50',
'relative',
'group',
)}
>
<div
className={cn(
'dark:bg-panelDark absolute right-2 z-[25] flex -translate-y-1/2 items-center gap-1 rounded-xl border bg-white p-1 opacity-0 shadow-sm group-hover:opacity-100',
index === 0 ? 'top-4' : 'top-[-1]',
)}
>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 overflow-visible [&_svg]:size-3.5"
onClick={handleToggleStar}
>
<Star2
className={cn(
'h-4 w-4',
displayStarred
? 'fill-yellow-400 stroke-yellow-400'
: 'fill-transparent stroke-[#9D9D9D] dark:stroke-[#9D9D9D]',
)}
/>
</Button>
</TooltipTrigger>
<TooltipContent
side={index === 0 ? 'bottom' : 'top'}
className="mb-1 bg-white dark:bg-[#1A1A1A]"
>
{displayStarred
? m['common.threadDisplay.unstar']()
: m['common.threadDisplay.star']()}
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className={cn(
'h-6 w-6 [&_svg]:size-3.5',
displayImportant ? 'hover:bg-orange-200/70 dark:hover:bg-orange-800/40' : '',
)}
onClick={handleToggleImportant}
>
<ExclamationCircle
className={cn(displayImportant ? 'fill-orange-400' : 'fill-[#9D9D9D]')}
/>
</Button>
</TooltipTrigger>
<TooltipContent
side={index === 0 ? 'bottom' : 'top'}
className="dark:bg-panelDark mb-1 bg-white"
>
{m['common.mail.toggleImportant']()}
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 [&_svg]:size-3.5"
onClick={(e) => {
e.stopPropagation();
moveThreadTo('archive');
}}
>
<Archive2 className="fill-[#9D9D9D]" />
</Button>
</TooltipTrigger>
<TooltipContent
side={index === 0 ? 'bottom' : 'top'}
className="dark:bg-panelDark mb-1 bg-white"
>
{m['common.threadDisplay.archive']()}
</TooltipContent>
</Tooltip>
{!isFolderBin ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 hover:bg-[#FDE4E9] dark:hover:bg-[#411D23] [&_svg]:size-3.5"
onClick={(e: React.MouseEvent) => {
e.stopPropagation();
moveThreadTo('bin');
}}
>
<Trash className="fill-[#F43F5E]" />
</Button>
</TooltipTrigger>
<TooltipContent
side={index === 0 ? 'bottom' : 'top'}
className="dark:bg-panelDark mb-1 bg-white"
>
{m['common.actions.Bin']()}
</TooltipContent>
</Tooltip>
) : null}
</div>
<div
className={`relative flex w-full items-center justify-between gap-4 px-4 ${displayUnread ? '' : 'opacity-60'}`}
>
<div>
<Avatar
className={cn(
'h-8 w-8 rounded-full',
displayUnread && !isMailSelected && !isFolderSent ? '' : 'border',
)}
>
<div
className={cn(
'flex h-full w-full items-center justify-center rounded-full bg-[#006FFE] p-2 dark:bg-[#006FFE]',
{
hidden: !isMailBulkSelected,
},
)}
onClick={(e: React.MouseEvent) => {
e.stopPropagation();
setMail((prev: Config) => ({
...prev,
bulkSelected: prev.bulkSelected.filter((id: string) => id !== idToUse),
}));
}}
>
<Check className="h-4 w-4 text-white" />
</div>
{isGroupThread ? (
<div className="flex h-full w-full items-center justify-center rounded-full bg-[#FFFFFF] p-2 dark:bg-[#373737]">
<GroupPeople className="h-4 w-4" />
</div>
) : (
<>
<AvatarImage
className="rounded-full bg-[#FFFFFF] dark:bg-[#373737]"
src={getEmailLogo(latestMessage.sender.email)}
alt={cleanName || latestMessage.sender.email}
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
}}
/>
<AvatarFallback
className="rounded-full bg-[#FFFFFF] font-bold text-[#9F9F9F] dark:bg-[#373737]"
delayMs={0}
>
{cleanName
? cleanName[0]?.toUpperCase()
: latestMessage.sender.email[0]?.toUpperCase()}
</AvatarFallback>
</>
)}
</Avatar>
{/* {displayUnread && !isMailSelected && !isFolderSent ? (
<>
<span className="absolute left-2 top-2 size-1.5 rounded bg-[#006FFE]" />
<span className="absolute left-[11px] top-4 size-1 rounded bg-[#006FFE]" />
</>
) : null} */}
</div>
<div className="flex w-full justify-between">
<div className="w-full">
<div className="flex w-full flex-row items-center justify-between">
<div className="flex flex-row items-center gap-[4px]">
<span
className={cn(
displayUnread && !isMailSelected ? 'font-bold' : 'font-medium',
'text-md flex items-baseline gap-1 group-hover:opacity-100',
)}
>
{isFolderSent ? (
<span
className={cn(
'overflow-hidden truncate text-sm md:max-w-[15ch] xl:max-w-[25ch]',
)}
>
{highlightText(latestMessage.subject, searchValue.highlight)}
</span>
) : (
<div className="flex items-center gap-1">
<span className={cn('line-clamp-1 overflow-hidden text-sm')}>
{highlightText(
cleanNameDisplay(latestMessage.sender.name) || '',
searchValue.highlight,
)}
</span>
{displayUnread && !isMailSelected && !isFolderSent ? (
<>
<span className="ml-0.5 size-2 rounded-full bg-[#006FFE]" />
</>
) : null}
</div>
)}{' '}
{/* {!isFolderSent ? (
<span className="hidden items-center space-x-2 md:flex">
<RenderLabels labels={threadLabels} />
</span>
) : null} */}
</span>
{getThreadData.totalReplies > 1 ? (
<Tooltip>
<TooltipTrigger asChild>
<span className="rounded-md text-xs opacity-70">
[{getThreadData.totalReplies}]
</span>
</TooltipTrigger>
<TooltipContent className="p-1 text-xs">
{m['common.mail.replies']({ count: getThreadData.totalReplies })}
</TooltipContent>
</Tooltip>
) : null}
{hasDraft ? (
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex items-center">
<PencilCompose className="h-3 w-3 fill-blue-500 dark:fill-blue-400" />
</span>
</TooltipTrigger>
<TooltipContent className="p-1 text-xs">Draft</TooltipContent>
</Tooltip>
) : null}
{/* {hasNotes ? (
<span className="inline-flex items-center">
<StickyNote className="h-3 w-3 fill-amber-500 stroke-amber-500 dark:fill-amber-400 dark:stroke-amber-400" />
</span>
) : null} */}
<MailLabels labels={optimisticLabels} />
</div>
{latestMessage.receivedOn ? (
<p
className={cn(
'text-muted-foreground text-nowrap text-xs font-normal opacity-70 transition-opacity group-hover:opacity-100 dark:text-[#8C8C8C]',
isMailSelected && 'opacity-100',
)}
>
{formatDate(latestMessage.receivedOn.split('.')[0] || '')}
</p>
) : null}
</div>
<div className="flex justify-between">
{isFolderSent ? (
<p
className={cn(
'mt-1 line-clamp-1 max-w-[50ch] overflow-hidden text-sm text-[#8C8C8C] md:max-w-[25ch]',
)}
>
{latestMessage.to.map((e) => e.email).join(', ')}
</p>
) : (
<p
className={cn(
'mt-1 line-clamp-1 w-[95%] min-w-0 overflow-hidden text-sm text-[#8C8C8C]',
)}
>
{highlightText(latestMessage.subject, searchValue.highlight)}
</p>
)}
{/* <div className="hidden md:flex">
{getThreadData.labels ? <MailLabels labels={getThreadData.labels} /> : null}
</div> */}
{threadLabels && (
<div className="mr-0 flex w-fit items-center justify-end gap-1">
{!isFolderSent ? <RenderLabels labels={threadLabels} /> : null}
{/* {getThreadData.labels ? <MailLabels labels={getThreadData.labels} /> : null} */}
</div>
)}
</div>
{emailContent && (
<div className="text-muted-foreground mt-2 line-clamp-2 text-xs">
{highlightText(emailContent, searchValue.highlight)}
</div>
)}
{/* {mainSearchTerm && (
<div className="text-muted-foreground mt-1 flex items-center gap-1 text-xs">
<span className="bg-primary/10 text-primary rounded px-1.5 py-0.5">
{mainSearchTerm}
</span>
</div>
)} */}
</div>
</div>
</div>
</div>
</div>
);
}, [
latestMessage,
getThreadData,
optimisticState,
idToUse,
folder,
isFolderBin,
isFolderSent,
isFolderSpam,
isFolderInbox,
onClick,
searchValue,
displayUnread,
isMailSelected,
isMailBulkSelected,
threadLabels,
optimisticLabels,
emailContent,
]);

Fix in CursorFix in Web


Bug: Stale Email Content Due to Missing Dependency

The useMemo hook calculates emailContent from getThreadData?.latest?.body, but this dependency is missing from its dependency array. This causes emailContent to become stale and display incorrect content when the thread body changes.

apps/mail/components/mail/mail-list.tsx#L94-L154

const { displayStarred, displayImportant, displayUnread, optimisticLabels, emailContent } =
useMemo(() => {
const emailContent = getThreadData?.latest?.body;
const displayStarred =
optimisticState.optimisticStarred !== null
? optimisticState.optimisticStarred
: (getThreadData?.latest?.tags?.some((tag) => tag.name === 'STARRED') ?? false);
const displayImportant =
optimisticState.optimisticImportant !== null
? optimisticState.optimisticImportant
: (getThreadData?.latest?.tags?.some((tag) => tag.name === 'IMPORTANT') ?? false);
const displayUnread =
optimisticState.optimisticRead !== null
? !optimisticState.optimisticRead
: (getThreadData?.hasUnread ?? false);
let labels: { id: string; name: string }[] = [];
if (getThreadData?.labels) {
labels = [...getThreadData.labels];
const hasStarredLabel = labels.some((label) => label.name === 'STARRED');
if (optimisticState.optimisticStarred !== null) {
if (optimisticState.optimisticStarred && !hasStarredLabel) {
labels.push({ id: 'starred-optimistic', name: 'STARRED' });
} else if (!optimisticState.optimisticStarred && hasStarredLabel) {
labels = labels.filter((label) => label.name !== 'STARRED');
}
}
if (optimisticState.optimisticLabels) {
labels = labels.filter(
(label) => !optimisticState.optimisticLabels.removedLabelIds.includes(label.id),
);
optimisticState.optimisticLabels.addedLabelIds.forEach((labelId) => {
if (!labels.some((label) => label.id === labelId)) {
labels.push({ id: labelId, name: labelId });
}
});
}
}
return {
displayStarred,
displayImportant,
displayUnread,
optimisticLabels: labels,
emailContent,
};
}, [
optimisticState.optimisticStarred,
optimisticState.optimisticImportant,
optimisticState.optimisticRead,
getThreadData?.latest?.tags,
getThreadData?.hasUnread,
getThreadData?.labels,
optimisticState.optimisticLabels,
]);

Fix in CursorFix in Web


Was this report helpful? Give feedback by reacting with 👍 or 👎

@coderabbitai coderabbitai bot mentioned this pull request Jul 8, 2025
34 tasks
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.

1 participant