Skip to Content
TelamonJS

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:

next.config.js
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:

HeavyLazy
Recharts (LineChart, BarChart, PieChart, AreaChart)LineChartLazy, BarChartLazy, PieChartLazy, AreaChartLazy
Code editorDynamicCodeEditor

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 cell renderers and field renderers: define them at module level — config.tsx is a module, so columns declared there are fine.

  • Keep non-primitive values stable. Prop defaults (items = []), columns, sections and option objects live at module level or in useMemo; an inline literal passed to a memoized component breaks the memo on every render.

  • useMemo only 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))), not useState(parse(...)), which runs on every render.

  • Interaction logic belongs in the handler. What happens "because the user clicked" goes in onClick, not in a useEffect watching state.

  • Non-urgent work: useDeferredValue(query) keeps an input responsive while filtering a large local list; useTransition replaces a hand-rolled isLoading state 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 />} renders 0; write {count > 0 ? <Badge /> : null}.

  • Client-only data without a flash. Theme, density and localStorage preferences that change the first paint are applied by an inline script in <head> before hydration, not in a useEffect (which flashes). Use suppressHydrationWarning only on the node that diverges on purpose.


6. JavaScript (low to medium)

  • Repeated lookups in a list (e.g. the option label in every relationship cell): build a Map once instead of a find per row.
  • Membership tests: Set.has, not array.includes inside a loop.
  • filter().map() over a large list: a single flatMap or loop.
  • Sort without mutating props or state: toSorted().
  • Create RegExps outside loops and render.

Generic advice that does not apply

Generic ruleWhy not hereUse instead
Dedupe requests with SWRData goes through React QueryCrudConfig.query / useQuery
Server Actions as the primary data layerThe app talks to a REST APIAPI client + backend guards
React.cache / LRU caches on the serverCaching lives in React Query and the backendstaleTime / invalidates
after() for non-blocking side effectsSide effects belong to the backendA background job (Queue)
Parallel fetching in Server ComponentsData is not fetched in Server ComponentsSection 2 above
Deep imports instead of barrelsThey lose types; the barrels are optimizableSection 1 above

On this page