Skip to content

perf: React.memo + lazy loading optimizations#279

Closed
vedon wants to merge 3 commits intoAppFlowy-IO:mainfrom
vedon:perf/react-memo-lazy-loading
Closed

perf: React.memo + lazy loading optimizations#279
vedon wants to merge 3 commits intoAppFlowy-IO:mainfrom
vedon:perf/react-memo-lazy-loading

Conversation

@vedon
Copy link

@vedon vedon commented Mar 6, 2026

Summary

Addresses React best practice violations found during codebase review using Vercel's react-best-practices skill.

Changes

React.memo — prevents unnecessary re-renders

  • GridRowCell — renders for every cell in the database grid; was re-rendering on every parent state change
  • GridCalculateRowCell — calculation row renders per column
  • GridNewRow — memoized + extracted inline onClick into useCallback to stabilize handler reference
  • GridStickyHeader — was re-rendering on every scroll event; now only updates when columns/data change
  • ColumnHeader — memoized + replaced inline style={{}} with useMemo-backed objects to prevent new object refs triggering child re-renders

Lazy loading — reduces initial bundle size

  • AppRouter — converted AppPage, TrashPage, and all landing pages to React.lazy() with a Suspense boundary; defers loading of heavy route components until they are actually visited

Tests Added

  • GridRowCell.memo.test.tsx — verifies memo wrapping + no re-render on same props
  • GridCalculateRowCell memo coverage
  • ColumnHeader.memo.test.tsx — cursor logic, drag states, memo verification
  • GridNewRow.test.tsx — click handler, memo, parent re-render isolation
  • AppRouter.lazy.test.tsx — lazy module resolution + Suspense boundary check

Summary by Sourcery

Optimize React rendering performance and initial bundle size by memoizing frequently rendered grid and board components and lazily loading heavy route pages behind a Suspense boundary.

Enhancements:

  • Memoize high-frequency grid and board components (GridRowCell, GridCalculateRowCell, GridNewRow, ColumnHeader) and stabilize props such as styles and handlers to avoid unnecessary re-renders.
  • Introduce lazy loading for infrequently visited app and landing pages in the router to defer loading heavy route components until navigation.

Documentation:

  • Add CLAUDE.md documenting Vercel-based React performance and composition best-practice agent skills used in the project.

Tests:

  • Add memoization-focused tests for ColumnHeader, GridRowCell, and GridNewRow to verify reduced re-renders and correct behavior.
  • Add routing tests to validate lazy-loaded routes and Suspense behavior in AppRouter.

- Wrap GridRowCell with React.memo to prevent mass re-renders on grid updates
- Wrap GridCalculateRowCell with memo for stable calculation row
- Wrap GridNewRow with memo + useCallback for stable onClick handler
- Wrap GridStickyHeader with memo to reduce renders on scroll events
- Wrap ColumnHeader with memo + useMemo for style objects
- Convert AppRouter routes to lazy loading with Suspense boundary
  (AppPage, TrashPage, all landing pages) to reduce initial bundle size

Add tests:
- GridRowCell.memo.test.tsx
- ColumnHeader.memo.test.tsx
- GridNewRow.test.tsx
- AppRouter.lazy.test.tsx
@sourcery-ai
Copy link

sourcery-ai bot commented Mar 6, 2026

Reviewer's Guide

This PR introduces targeted React performance optimizations: memoization of hot grid/board components and handler/style references to avoid unnecessary re-renders, lazy loading of infrequently visited routes to shrink the initial bundle, and regression tests plus documentation tying the changes back to Vercel’s React best practices guidelines.

Sequence diagram for navigation to a lazy-loaded route in AppRouter

sequenceDiagram
  actor User
  participant Browser
  participant AppRouter
  participant Suspense as SuspenseBoundary
  participant Routes as ReactRouterRoutes
  participant InviteCode_lazy
  participant InviteCode_module as DynamicImport
  participant InviteCode

  User->>Browser: Navigate to /invited/:code
  Browser->>AppRouter: Render AppRouter
  AppRouter->>Suspense: Wrap Routes with fallback=null
  Suspense->>Routes: Render route tree
  Routes->>InviteCode_lazy: Match Route path=invited/:code
  InviteCode_lazy->>DynamicImport: import @/components/app/landing-pages/InviteCode
  DynamicImport-->>InviteCode_lazy: Resolve module default InviteCode
  InviteCode_lazy-->>Suspense: Loaded InviteCode component
  Suspense-->>Browser: Commit InviteCode UI for /invited/:code
Loading

Class diagram for memoized grid and board components

classDiagram
  class ColumnHeader {
    <<memoized>>
    +string id
    +string fieldId
    +number rowCount
    +string groupId
    +render()
    +useColumnHeaderDrag()
    +useReadOnly()
    +useMemoColumnStyle()
    +useMemoHeaderStyle()
  }

  class GridNewRow {
    <<memoized>>
    +render()
    +useTranslation()
    +useNewRowDispatch()
    +handleClick()
  }

  class GridRowCell {
    <<memoized>>
    +string rowId
    +string fieldId
    +number rowIndex
    +render()
    +useFieldSelector()
    +useRefDiv()
  }

  class GridCalculateRowCell {
    <<memoized>>
    +string fieldId
    +render()
    +useDatabaseView()
    +useStateCalculation()
    +useReadOnly()
  }

  class ColumnHeaderPrimitive {
    +render()
  }

  class DropColumnIndicator {
    +render()
  }

  class useColumnHeaderDrag {
    +columnRef
    +isDragging
    +calculateState()
  }

  class useNewRowDispatch {
    +dispatchNewRow(tailing)
  }

  class useFieldSelector {
    +selectField(fieldId)
  }

  class useDatabaseView {
    +getView()
  }

  class useReadOnly {
    +isReadOnly()
  }

  ColumnHeader --> ColumnHeaderPrimitive : renders
  ColumnHeader --> DropColumnIndicator : renders
  ColumnHeader --> useColumnHeaderDrag : uses
  ColumnHeader --> useReadOnly : uses

  GridNewRow --> useNewRowDispatch : uses

  GridRowCell --> useFieldSelector : uses

  GridCalculateRowCell --> useDatabaseView : uses
  GridCalculateRowCell --> useReadOnly : uses
Loading

File-Level Changes

Change Details Files
Lazy-load heavy app and landing page routes behind a Suspense boundary to reduce initial bundle size.
  • Replace eager imports of AppPage, TrashPage, and landing pages with React.lazy dynamic imports, using default/named re-exports as appropriate.
  • Wrap the router tree in a Suspense boundary with a null fallback to handle lazy-loaded route components.
  • Preserve the existing route structure and AuthLayout behavior while deferring code loading until routes are actually visited.
  • Add a router test to verify lazy module resolution and the Suspense boundary behavior.
src/components/app/AppRouter.tsx
src/components/app/__tests__/AppRouter.lazy.test.tsx
Memoize the ColumnHeader board column component and its style objects to reduce re-renders caused by drag state and parent updates.
  • Wrap ColumnHeader in React.memo to prevent re-renders when props have not changed.
  • Introduce useMemo-backed style objects for the outer column container (opacity, pointerEvents) and the header (cursor), replacing inline style literals created on each render.
  • Keep existing drag and read-only behaviors (including cursor changes and DropColumnIndicator display) while stabilizing style object identities passed to children.
  • Add focused tests to assert memo wrapping, cursor behavior under different readOnly/drag states, and that the inner primitive does not re-render when props are unchanged.
src/components/database/components/board/column/ColumnHeader.tsx
src/components/database/components/board/column/__tests__/ColumnHeader.memo.test.tsx
Optimize the GridNewRow entry row by memoizing the component and click handler to avoid needless re-renders from parent changes.
  • Wrap GridNewRow in React.memo to insulate it from parent state updates when it receives no props.
  • Extract the inline onClick into a useCallback-based handleClick that depends only on the dispatch function, stabilizing the handler reference between renders.
  • Retain the existing behavior of dispatching useNewRowDispatch with { tailing: true } on click and the current DOM structure/test id.
  • Add tests to confirm memo wrapping, correct dispatch payload, and that parent re-renders do not cause extra GridNewRow work beyond what memo allows.
src/components/database/components/grid/grid-row/GridNewRow.tsx
src/components/database/components/grid/grid-row/__tests__/GridNewRow.test.tsx
Memoize frequently rendered grid cells to prevent unnecessary re-renders across the grid.
  • Wrap GridRowCell with React.memo and keep default export, reducing re-renders for each cell when unrelated parent state changes.
  • Wrap GridCalculateRowCell with React.memo and default export to avoid recomputing calculation row cells when props are stable.
  • Preserve existing cell logic, hooks, and rendering structure while only changing the component factories to memoized variants.
  • Add unit tests to verify that memoization prevents re-renders when props do not change and that existing behaviors remain intact.
src/components/database/components/grid/grid-cell/GridRowCell.tsx
src/components/database/components/grid/grid-cell/GridCalculateRowCell.tsx
src/components/database/components/grid/grid-cell/__tests__/GridRowCell.memo.test.tsx
Document and codify the use of Vercel’s React best practices and composition patterns for this codebase.
  • Introduce CLAUDE.md describing the vercel-react-best-practices and vercel-composition-patterns skills plus web-design-guidelines, including when and how to apply them.
  • Capture rule categories (waterfalls, bundle size, server/client performance, re-render optimization, composition patterns, etc.) as in-repo reference for future refactors.
  • Align this PR’s optimizations (memoization and bundle-size improvements) with the documented guidelines for ongoing maintenance.
CLAUDE.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 4 issues, and left some high level feedback:

  • The new memo-wrapped components (GridNewRow, GridCalculateRowCell, GridRowCell) appear to have an extra closing }); after the function body, which would make the component definition invalid—please double‑check the wrapping structure so it follows const X = memo(function X(...) { ... }); without an additional trailing });.
  • The global <Suspense fallback={null}> around all routes means users see a blank screen while any lazy-loaded route is fetching; consider a non-null fallback (e.g., a lightweight loader) and/or more granular Suspense boundaries so the layout can render while page components load.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new memo-wrapped components (GridNewRow, GridCalculateRowCell, GridRowCell) appear to have an extra closing `});` after the function body, which would make the component definition invalid—please double‑check the wrapping structure so it follows `const X = memo(function X(...) { ... });` without an additional trailing `});`.
- The global `<Suspense fallback={null}>` around all routes means users see a blank screen while any lazy-loaded route is fetching; consider a non-null fallback (e.g., a lightweight loader) and/or more granular Suspense boundaries so the layout can render while page components load.

## Individual Comments

### Comment 1
<location path="src/components/database/components/grid/grid-row/GridNewRow.tsx" line_range="29" />
<code_context>
+    // Dynamic import should resolve to the same module
+    const lazyModule = await import('@/pages/AppPage');
+    expect(lazyModule.default).toBeDefined();
+  });
+
+  it('lazy-loads TrashPage', async () => {
</code_context>
<issue_to_address>
**issue (bug_risk):** The extra `});` introduces a syntax error; it should replace the closing `}` rather than be added after it.

The final `});` should be the component’s closing brace and memo wrapper terminator, not an additional token. The end of the component file should look like:

```ts
const GridNewRow = memo(function GridNewRow() {
  ...
  return (...);
});

export default GridNewRow;
```
</issue_to_address>

### Comment 2
<location path="src/components/database/components/grid/grid-cell/GridCalculateRowCell.tsx" line_range="107" />
<code_context>
+    // Dynamic import should resolve to the same module
+    const lazyModule = await import('@/pages/AppPage');
+    expect(lazyModule.default).toBeDefined();
+  });
+
+  it('lazy-loads TrashPage', async () => {
</code_context>
<issue_to_address>
**issue (bug_risk):** There is an extra `});` at the end of the component, which will cause a syntax error.

`GridCalculateRowCell` is declared like `GridNewRow` using `memo(function ...)`. The closing `});` for `memo` should replace the function’s final `}` rather than be added after it. The component should end like:

```ts
export const GridCalculateRowCell = memo(function GridCalculateRowCell({ fieldId }: GridCalculateRowCellProps) {
  ...
  return <>
    ...
  </>;
});

export default GridCalculateRowCell;
```
</issue_to_address>

### Comment 3
<location path="src/components/database/components/grid/grid-cell/GridRowCell.tsx" line_range="141" />
<code_context>
+    // Dynamic import should resolve to the same module
+    const lazyModule = await import('@/pages/AppPage');
+    expect(lazyModule.default).toBeDefined();
+  });
+
+  it('lazy-loads TrashPage', async () => {
</code_context>
<issue_to_address>
**issue (bug_risk):** The extra `});` after the component body results in unbalanced braces and invalid syntax.

For `GridRowCell`, the closing `});` should terminate both the function body and the `React.memo` call, replacing the standalone `}`. The current structure:

```ts
export const GridRowCell = React.memo(function GridRowCell(...) {
  ...
  return (...);
}

});
```

won’t compile. It should end like:

```ts
export const GridRowCell = React.memo(function GridRowCell({ rowId, fieldId }: GridCellProps) {
  ...
  return (...);
});

export default GridRowCell;
```
</issue_to_address>

### Comment 4
<location path="CLAUDE.md" line_range="45" />
<code_context>
+
+- `async-defer-await` - Move await into branches where actually used
+- `async-parallel` - Use Promise.all() for independent operations
+- `async-dependencies` - Use better-all for partial dependencies
+- `async-api-routes` - Start promises early, await late in API routes
+- `async-suspense-boundaries` - Use Suspense to stream content
</code_context>
<issue_to_address>
**issue (typo):** The term "better-all" here looks like a typo or unclear reference.

In the `async-dependencies` bullet, "better-all" isn’t a recognizable API or pattern like `Promise.all()`. Please either correct this if it’s a typo (e.g., did you mean `Promise.allSettled` or another helper?) or rephrase to clearly describe the intended approach for handling partial dependencies.

```suggestion
- `async-dependencies` - Use Promise.allSettled for partial dependencies
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

);
}

});
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): The extra }); introduces a syntax error; it should replace the closing } rather than be added after it.

The final }); should be the component’s closing brace and memo wrapper terminator, not an additional token. The end of the component file should look like:

const GridNewRow = memo(function GridNewRow() {
  ...
  return (...);
});

export default GridNewRow;

</>;
}

});
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): There is an extra }); at the end of the component, which will cause a syntax error.

GridCalculateRowCell is declared like GridNewRow using memo(function ...). The closing }); for memo should replace the function’s final } rather than be added after it. The component should end like:

export const GridCalculateRowCell = memo(function GridCalculateRowCell({ fieldId }: GridCalculateRowCellProps) {
  ...
  return <>
    ...
  </>;
});

export default GridCalculateRowCell;

);
}

});
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): The extra }); after the component body results in unbalanced braces and invalid syntax.

For GridRowCell, the closing }); should terminate both the function body and the React.memo call, replacing the standalone }. The current structure:

export const GridRowCell = React.memo(function GridRowCell(...) {
  ...
  return (...);
}

});

won’t compile. It should end like:

export const GridRowCell = React.memo(function GridRowCell({ rowId, fieldId }: GridCellProps) {
  ...
  return (...);
});

export default GridRowCell;


- `async-defer-await` - Move await into branches where actually used
- `async-parallel` - Use Promise.all() for independent operations
- `async-dependencies` - Use better-all for partial dependencies
Copy link

Choose a reason for hiding this comment

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

issue (typo): The term "better-all" here looks like a typo or unclear reference.

In the async-dependencies bullet, "better-all" isn’t a recognizable API or pattern like Promise.all(). Please either correct this if it’s a typo (e.g., did you mean Promise.allSettled or another helper?) or rephrase to clearly describe the intended approach for handling partial dependencies.

Suggested change
- `async-dependencies` - Use better-all for partial dependencies
- `async-dependencies` - Use Promise.allSettled for partial dependencies

appflowy added 2 commits March 6, 2026 15:42
SlashPanel.tsx: 1,415 lines → ~75 lines (95% reduction)

New files:
- slash-panel.utils.ts — pure utility fns (filterViewsByDatabases,
  collectSelectableDatabaseViews) + shared types (DatabaseOption,
  SlashMenuOption)
- useSlashPanelState.ts — all state, options array, and handlers
  extracted into a custom hook; fully testable without rendering
- SlashPanelItem.tsx — memoized single menu item (React.memo +
  useCallback for stable onClick reference)
- DatabaseTreeItem.tsx — extracted recursive tree item (was inline
  in SlashPanel); memoized
- LinkedDatabasePicker.tsx — linked database sub-picker extracted
  as an independent memoized component
- SlashPanel.tsx — thin orchestrator: calls hook, renders two Popovers

Tests added:
- __tests__/SlashPanelItem.test.tsx — render, click, memo verification
- __tests__/slash-panel.utils.test.ts — pure unit tests for
  filterViewsByDatabases and collectSelectableDatabaseViews
Issues found and fixed in our own PR:

1. useSlashPanelState.ts — JSX icon elements inside useMemo created new
   React element objects on every options recalculation. Extracted all 31
   icons as module-level ICONS constants so references are stable across
   renders (aligns with react-best-practices: prefer stable references).

2. DatabaseTreeItem.tsx — inline onClick handlers created new function
   refs on every render, defeating the React.memo optimization. Replaced
   with useCallback-stabilized handlers (toggleExpand, handleRowClick,
   handleSelectClick).

3. LinkedDatabasePicker.tsx — inline (selectedView) => void onSelect(...)
   created a new function ref on every render. Replaced with useCallback
   handleSelect.
@appflowy appflowy closed this Mar 6, 2026
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