Performance
React and Next.js performance rules for TelamonJS apps — bundle, request waterfalls, re-renders and rendering
A checklist for writing or reviewing a component, form, list page or dashboard. It adapts
Vercel's React best practices
to the TelamonJS architecture (React Query + a REST API, CrudConfig, Zustand), keeping only the
rules that apply here.
Correctness first
No rule on this page justifies breaking one of the other patterns. When they disagree, the pattern wins.
1. Bundle (critical)
Optimize barrels instead of deep imports
@telamonjs/ui, lucide-react and @radix-ui/* are barrels. Import from them normally
and let Next.js rewrite the imports:
experimental: {
optimizePackageImports: ['@telamonjs/ui', 'lucide-react'],
}Don't switch to deep imports (lucide-react/dist/esm/icons/...): they lose their types under
strict. Apps generated by the CLI already ship this config. It also keeps a single react-query
instance: see Troubleshooting.
Load heavy components lazily
The library ships lazy versions; use them below the fold:
| Heavy | Lazy |
|---|---|
Recharts (LineChart, BarChart, PieChart, AreaChart) | LineChartLazy, BarChartLazy, PieChartLazy, AreaChartLazy |
| Code editor | DynamicCodeEditor |
Load on use
Content of a rarely opened dialog, tab or panel goes behind an import() triggered when it opens,
not at the top of the file. To make it feel instant, start the import() on the opening button's
onMouseEnter/onFocus.
2. Request waterfalls (critical)
Promise.all for independent awaits
This applies to any queryFn/mutationFn that makes more than one call:
// ❌ two round-trips in series
const user = await usersApi.get(id)
const roles = await rolesApi.list()
// ✅ in parallel
const [user, roles] = await Promise.all([usersApi.get(id), rolesApi.list()])await only in the branch that needs it
Don't await a value before an if that can return early without it.
Independent queries don't chain
Two useQuery calls without a real dependency run in parallel. Use enabled: !!x only when the
second query truly needs the first one's result — an artificial dependency is an invisible
waterfall.
One boundary per data region
Wrap each data region in its own DataBoundary (error boundary + Suspense + empty state) instead
of one boundary for the whole page, so whatever arrives first shows first.
3. Server/Client boundary (high)
Everything that crosses from a Server Component to a Client Component is serialized into the HTML.
Pass { id, name }, not the whole entity, and never pass the same object twice under different
props.
4. Re-renders (medium)
-
Derive state during render, not in
useEffect.// ❌ an extra render and duplicated state const [fullName, setFullName] = useState('') useEffect(() => setFullName(`${first} ${last}`), [first, last]) // ✅ const fullName = `${first} ${last}` -
Never declare a component inside a component. It remounts on every render, losing focus and state. This includes column
cellrenderers and field renderers: define them at module level —config.tsxis a module, socolumnsdeclared there are fine. -
Keep non-primitive values stable. Prop defaults (
items = []),columns,sectionsand option objects live at module level or inuseMemo; an inline literal passed to a memoized component breaks the memo on every render. -
useMemoonly for expensive work. A simple expression with a primitive result (a + b,list.length > 0) doesn't need it. -
Functional
setState—setCount(c => c + 1)keeps callbacks stable and avoids stale closures. -
Lazy initial state —
useState(() => parse(localStorage.getItem(key))), notuseState(parse(...)), which runs on every render. -
Interaction logic belongs in the handler. What happens "because the user clicked" goes in
onClick, not in auseEffectwatching state. -
Non-urgent work:
useDeferredValue(query)keeps an input responsive while filtering a large local list;useTransitionreplaces a hand-rolledisLoadingstate for actions. -
Transient values in
useRef— scroll or mouse position, timers, the last seen value. -
Zustand: never use a dynamic selector inside a custom hook — see Zustand Selector Pattern, which takes precedence over the generic "subscribe to derived state" advice.
5. Rendering (medium)
-
Long lists outside a paginated table (hundreds of rows or tree nodes):
.row { content-visibility: auto; contain-intrinsic-size: 0 48px; } -
Ternary, not
&&, with numbers.{count && <Badge />}renders0; write{count > 0 ? <Badge /> : null}. -
Client-only data without a flash. Theme, density and
localStoragepreferences that change the first paint are applied by an inline script in<head>before hydration, not in auseEffect(which flashes). UsesuppressHydrationWarningonly on the node that diverges on purpose.
6. JavaScript (low to medium)
- Repeated lookups in a list (e.g. the option label in every
relationshipcell): build aMaponce instead of afindper row. - Membership tests:
Set.has, notarray.includesinside a loop. filter().map()over a large list: a singleflatMapor loop.- Sort without mutating props or state:
toSorted(). - Create
RegExps outside loops and render.
Generic advice that does not apply
| Generic rule | Why not here | Use instead |
|---|---|---|
| Dedupe requests with SWR | Data goes through React Query | CrudConfig.query / useQuery |
| Server Actions as the primary data layer | The app talks to a REST API | API client + backend guards |
React.cache / LRU caches on the server | Caching lives in React Query and the backend | staleTime / invalidates |
after() for non-blocking side effects | Side effects belong to the backend | A background job (Queue) |
| Parallel fetching in Server Components | Data is not fetched in Server Components | Section 2 above |
| Deep imports instead of barrels | They lose types; the barrels are optimizable | Section 1 above |
Related
- Provider Setup — one
QueryClientfor the app and the library - Troubleshooting — two copies of a peer dependency
- Dashboard Pattern — memoized stats, virtualized side lists
- Zustand Selector Pattern