Next.js and SSR
The 'use client' boundary in the App Router, what the server renders, dark mode, initial state from the URL, and the scroll position when you navigate back
The grid is a client component that uses hooks. It renders without errors or warnings on the server (SSR / SSG), but the table's contents appear after hydration. This page covers the rules and things to keep in mind when you use it with Next.js (App Router).
The 'use client' boundary
Put the component that renders the grid in a 'use client' file.
// app/orders/orders-grid.tsx
'use client';
import { useState } from 'react';
import { SpreadsheetGrid, type GridColumn } from '@ishibashi0112/spreadsheet-grid';
import '@ishibashi0112/spreadsheet-grid/style.css';
import type { Order } from './types';
const columns: GridColumn<Order>[] = [
{ key: 'name', title: 'Item', width: 200 },
{ key: 'amount', title: 'Amount', width: 140, valueFormatter: ({ value }) => `$${Number(value).toLocaleString()}` },
];
export function OrdersGrid({ initialRows }: { initialRows: Order[] }) {
const [rows, setRows] = useState(initialRows);
return <SpreadsheetGrid rows={rows} onRowsChange={setRows} columns={columns} rowKeyGetter={(row) => row.id} />;
}// app/orders/page.tsx (a server component)
import { OrdersGrid } from './orders-grid';
export default async function Page() {
const orders = await getOrders(); // from a database or an API
return <OrdersGrid initialRows={orders} />;
}A server component can't pass functions to a client component as props. The following contain functions, so create or import them inside a 'use client' file (if you create them on the server and pass them down, the page returns a 500 when opened, and static pages fail to build. The types still check, so you won't notice while writing the code).
| Contains functions | Where to put it |
|---|---|
Column definitions (columns with valueFormatter / renderCell / validate / getValue and so on) | A 'use client' file |
Column groups (columnGroups) with renderHeader | A 'use client' file (definitions without renderHeader can be passed from the server) |
The English text tables localeTextEn / gridAskLocaleTextEn | Import them in a 'use client' file, and pass only the language ('ja' / 'en') from the server (English and text) |
A grid made with createSpreadsheetGrid from /lite, and standardFeatures | Add 'use client' to the file that calls createSpreadsheetGrid (reduce the bundle size) |
serverSide's dataSource, and the AI bar's ask | A 'use client' file (that fetches your own Route Handler) |
Row data (values without functions) can be created on the server and passed down. The date editor reads and writes 'YYYY-MM-DD' strings, so if you turn date values into strings on the server, they keep the same shape after editing.
You can load the CSS (style.css) in app/layout.tsx or in the 'use client' file that renders the grid. For loading it together with Tailwind CSS, see Loading the CSS and coexistence.
What the server renders
The HTML rendered on the server is the table's skeleton.
- Only the row numbers and the cells of pinned columns (
pinned) are rendered. Columns that aren't pinned (subject to horizontal virtualization) render after hydration. A table without pinned columns shows only row numbers until hydration. - Where JavaScript doesn't run, the table's contents don't appear. On pages where you want search engines to read the table's contents, add an HTML table or text separately from the grid.
initialState(initial sorting, filtering and column widths) takes effect from the server render (Saving and restoring state).
Dark mode
theme="auto"(follow the OS color scheme) renders light on the server and switches to the client's scheme after hydration. On a dark OS, a light table flashes briefly.- On pages that switch to dark with
<html class="dark">(next-themes and the like), usetheme="class". The grid's colors are then decided by CSS alone, so it is dark from the server render. motion="auto"works the same way: the server renders with animations, and after hydration the grid checks the "reduce motion" setting and decides again.
cacheComponents (Next.js 16)
- A page with only the grid can render as a static page without wrapping it in
<Suspense>. - If you render with a date column condition (
dateSet'scondition) ininitialState, wrap it in<Suspense>, because resolving the condition reads today's date. - Put the part that reads
searchParamsinside<Suspense>(a Next.js rule). Wrap it inside the page, not inlayout.tsx(wrapped inlayout.tsx, the build passes, but in development you get a console.error saying "searchParams accessed outside of<Suspense>").
Setting the initial state from the URL
To set sorting or filtering from a URL such as ?sort=qty.desc, read searchParams in a server component and pass it to initialState. Sorting then applies from the server render. There is an example in Saving and restoring state: restoring from the URL.
State saved in localStorage can't be read on the server. Reading it during render makes the server and client HTML differ, so render screens that open from saved state on the client only (ssr: false with next/dynamic and the like), or keep the state on the server (user settings, for example) and pass it as props.
Scroll position when you go back to the previous page
When you go back to the previous page with Next.js 16 (cacheComponents) navigation, the grid's state (filters, selection, an edit in progress) is kept, but the vertical scroll position may return to the top (for example after moving with <Link>: when Next.js re-inserts the elements of the hidden page, the browser drops the scroll position. If the page is only hidden and shown with a plain <Activity>, the position is kept).
To restore the position too, remember it in onScroll, and when the page becomes visible, restore it with the handle's setScrollPosition in useLayoutEffect (with useEffect, an onScroll for the position reset to the top can arrive before you restore it and overwrite the remembered position with 0).
const gridRef = useRef<SpreadsheetGridHandle<Row>>(null);
const scroll = useRef({ top: 0, left: 0 });
// when the page becomes visible (layout effects run each time the page is shown), restore before paint
useLayoutEffect(() => {
gridRef.current?.setScrollPosition(scroll.current);
}, []);
<SpreadsheetGrid
ref={gridRef}
onScroll={({ top, left }) => { scroll.current = { top, left }; }}
...
/>Server APIs
- serverSide (SSRM):
dataSource.getRowsfetches your own Route Handler (app/api/orders/route.tsand so on). The demo in Server-side row model on this site calls a real Next.js Route Handler. - Filter with words (
/ai): so that your AI API key never reaches the browser, call your own Route Handler fromaskand call the AI there. Route Handler examples for Claude / OpenAI / Gemini / the Vercel AI SDK are in Filter with words.