Section 12 of 17

React and Next.js

Contents

The architecture does not depend on Angular. Libraries, types, domains, tags and the lint rule stay the same; Nx generates React and Next.js projects with @nx/react and @nx/next. What changes is how each library type is implemented, and Next.js adds one new dimension: code that runs only on the server.

We split state into two kinds. Server state, data the back-end owns (the work order list), is held by TanStack Query. Client state, what exists only in the browser (filter criteria, selections, drafts), is held by Zustand. Both are private to data-access, and the feature sees only the facade.

The same workspace with a Next.js application, and every file of this use case:

fleetline/
├── nx.json
├── package.json
├── tsconfig.base.json
├── eslint.config.mjs
├── apps/
│   └── customer/
│       ├── project.json
│       ├── next.config.js
│       ├── tsconfig.json
│       ├── public/
│       └── app/
│           ├── layout.tsx
│           ├── page.tsx
│           └── maintenance/
│               ├── layout.tsx
│               └── depots/
│                   └── [depotId]/
│                       └── work-orders/
│                           ├── page.tsx
│                           └── loading.tsx
└── libs/
    ├── maintenance/
    │   ├── feature-shell/
    │   │   └── src/
    │   │       ├── index.ts
    │   │       └── lib/
    │   │           └── maintenance-layout.tsx
    │   ├── feature-work-orders/
    │   │   └── src/
    │   │       ├── index.ts
    │   │       └── lib/
    │   │           ├── work-orders-route.tsx
    │   │           ├── work-orders-page.tsx
    │   │           └── work-orders-page.spec.tsx
    │   ├── ui-work-order-card/
    │   │   └── src/
    │   │       ├── index.ts
    │   │       └── lib/
    │   │           ├── work-order-card.tsx
    │   │           ├── work-order-card.module.scss
    │   │           └── status-filter.tsx
    │   ├── data-access/
    │   │   ├── project.json
    │   │   ├── tsconfig.json
    │   │   └── src/
    │   │       ├── index.ts
    │   │       └── lib/
    │   │           ├── work-orders.http.ts
    │   │           ├── work-orders.queries.ts
    │   │           ├── work-orders.mutations.ts
    │   │           ├── work-orders.store.ts
    │   │           ├── work-orders.store.spec.ts
    │   │           ├── work-orders.provider.tsx
    │   │           └── use-work-orders.ts
    │   ├── data-access-server/
    │   │   └── src/
    │   │       ├── index.ts
    │   │       └── lib/
    │   │           └── work-orders.ts
    │   └── model/
    │       └── src/
    │           ├── index.ts
    │           └── lib/
    │               └── work-order.ts
    ├── fleet/
    │   ├── api/
    │   │   └── src/
    │   │       └── index.ts
    │   └── data-access/
    │       └── src/
    │           └── lib/
    │               ├── fleet.http.ts
    │               ├── vehicle-summary.store.ts
    │               └── vehicle-summaries.tsx
    ├── identity/
    │   └── api/
    └── shared/
        ├── data-access-query/
        │   └── src/
        │       ├── index.ts
        │       └── lib/
        │           ├── query-client.ts
        │           └── query-provider.tsx
        ├── data-access-server/
        ├── ui-design-system/
        ├── util-http/
        └── util-date/

12.1. What maps to what

Angular React / Next.js
feature component A server container that loads the data and a client component that displays it; both in feature-*, and page.tsx only renders the container
ui component with input()/output() A component with props and callbacks
shell routes File routes stay in apps/<app>/app/; the shell library exports the domain's layout with providers and the permission check
provideWorkOrders() on a route <WorkOrdersProvider> in the shell layout
NgRx Store and effects for server data TanStack Query: queryOptions, useQuery, useMutation
Signal Store for client state Zustand: createStore from a factory, shared through Context
createSelector A selector in useStore(store, selector); the facade computes derived values and the React Compiler memoizes them
switchMap in an effect The query key and signal in queryFn
Optimistic reducer and assignFailed onMutate and onError in useMutation
Facade service A hook: useWorkOrders()
@Service() with HttpClient A module of functions over createApiClient from shared/util-http
inject() Context read with use(), only for things that have a scope
provideStoreDevtools Zustand's devtools middleware and React Query Devtools

Redux Toolkit fits this architecture too: a slice instead of an NgRx feature, createEntityAdapter, listener middleware instead of effects. Fleetline chose TanStack Query and Zustand because in Next.js most state is server state, and what remains on the client is small (section 17).

12.2. Tags for server and client

In the App Router a file is either a server component or a client component. Code that reads secrets, cookies or the database must never end up in the browser bundle. Fleetline adds a second data-access library per domain and one more tag:

Library Tags Contains
maintenance/data-access type:data-access, platform:client HTTP client, TanStack Query queries and mutations, Zustand store, provider, facade hook
maintenance/data-access-server type:data-access, platform:server server-only fetch functions and server actions

The lint rule from section 8.2 already contains the constraint platform:client → not platform:server. Every server-only file also starts with import 'server-only', so a mistake fails the build even where lint does not run. The feature library has no platform tag: its server container imports data-access-server, and its client component only data-access.

12.3. HTTP and the query client

React has no DI, so the HTTP service is a plain module. createApiClient from shared/util-http is a thin, framework-free wrapper over fetch: base URL, JSON, and HTTP errors as exceptions. The module holds only configuration, never user data, so it can live at module level.

libs/maintenance/data-access/src/lib/work-orders.http.ts

import { createApiClient } from '@fleetline/shared/util-http';
import type { WorkOrder } from '@fleetline/maintenance/model';

const api = createApiClient(process.env.NEXT_PUBLIC_API_URL ?? '');

export const workOrdersHttp = {
  list: (depotId: string, signal?: AbortSignal) =>
    api.get<WorkOrder[]>(`/depots/${depotId}/work-orders`, { signal }),
  assign: (id: string, assigneeId: string) =>
    api.put<WorkOrder>(`/work-orders/${id}/assignee`, { assigneeId }),
};

The query cache, unlike configuration, holds user data. That is why the QueryClient is created in a provider: one per browser tab and a separate one for every request on the server. The application's root layout mounts QueryProvider once, like provideHttpClient() in Angular's app.config.ts.

libs/shared/data-access-query/src/lib/query-client.ts

import { QueryClient } from '@tanstack/react-query';

export function makeQueryClient() {
  return new QueryClient({ defaultOptions: { queries: { staleTime: 60_000 } } });
}

libs/shared/data-access-query/src/lib/query-provider.tsx

'use client';

import { useState, type ReactNode } from 'react';
import { QueryClientProvider } from '@tanstack/react-query';
import { makeQueryClient } from './query-client';

export function QueryProvider({ children }: { children: ReactNode }) {
  const [client] = useState(makeQueryClient);
  return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
}

12.4. Queries and mutations

libs/maintenance/data-access/src/lib/work-orders.queries.ts

import { queryOptions } from '@tanstack/react-query';
import { workOrdersHttp } from './work-orders.http';

export const workOrdersQuery = (depotId: string) =>
  queryOptions({
    queryKey: ['maintenance', 'work-orders', depotId],
    queryFn: ({ signal }) => workOrdersHttp.list(depotId, signal),
  });

The key contains depotId, and queryFn passes signal to fetch. Switching the depot abandons the old query and aborts its request: the switchMap semantics from section 9.4. Two components that read the same key share one request and one cache entry. The file has no 'use client', because the server container imports workOrdersQuery too (section 12.7).

libs/maintenance/data-access/src/lib/work-orders.mutations.ts

'use client';

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { workOrdersHttp } from './work-orders.http';
import { workOrdersQuery } from './work-orders.queries';

export function useAssignWorkOrder(depotId: string) {
  const client = useQueryClient();
  const { queryKey } = workOrdersQuery(depotId);

  return useMutation({
    mutationFn: ({ id, assigneeId }: { id: string; assigneeId: string }) => workOrdersHttp.assign(id, assigneeId),
    onMutate: async ({ id, assigneeId }) => {
      await client.cancelQueries({ queryKey });
      const previous = client.getQueryData(queryKey);
      client.setQueryData(queryKey, (orders) =>
        orders?.map((order) => (order.id === id ? { ...order, assigneeId } : order)),
      );
      return { previous };
    },
    onError: (_error, _variables, context) => client.setQueryData(queryKey, context?.previous),
    onSettled: () => client.invalidateQueries({ queryKey }),
  });
}

The same optimistic update as in section 9.3: onMutate writes the new mechanic at once, onError restores the previous list, and onSettled refetches the state from the server. Mutations do not cancel each other, so two assignments on two cards both finish, as with mergeMap.

12.5. Client state in Zustand

libs/maintenance/data-access/src/lib/work-orders.store.ts

import { createStore } from 'zustand/vanilla';
import { devtools } from 'zustand/middleware';
import type { WorkOrderFilter } from '@fleetline/maintenance/model';

type Criteria = Omit<WorkOrderFilter, 'depotId'>;

export interface WorkOrdersClientState {
  criteria: Criteria;
  filterChanged: (change: Partial<Criteria>) => void;
}

export function createWorkOrdersStore() {
  return createStore<WorkOrdersClientState>()(
    devtools(
      (set) => ({
        criteria: { status: 'all', query: '' },
        filterChanged: (change) =>
          set((state) => ({ criteria: { ...state.criteria, ...change } }), undefined, 'Work Orders Page/filterChanged'),
      }),
      { name: 'maintenance/work-orders' },
    ),
  );
}

export type WorkOrdersStore = ReturnType<typeof createWorkOrdersStore>;

Zustand holds only what the client owns: the filter criteria. The work order list lives in the query cache and is not copied here, because two sources of truth drift apart sooner or later. Actions are named like the events from section 9.2 (filterChanged, not setFilter), and the third argument of set records that event in Redux DevTools, so the event log stays, even without reducers.

The store is built by the createStore factory, not by create() at module level. On the server, a global store in Next.js would be shared by all requests, that is, by all users. The factory is called by a provider:

libs/maintenance/data-access/src/lib/work-orders.provider.tsx

'use client';

import { createContext, use, useState, type ReactNode } from 'react';
import { createWorkOrdersStore, type WorkOrdersStore } from './work-orders.store';

const WorkOrdersStoreContext = createContext<WorkOrdersStore | null>(null);

export function WorkOrdersProvider({ children }: { children: ReactNode }) {
  const [store] = useState(createWorkOrdersStore);
  return <WorkOrdersStoreContext value={store}>{children}</WorkOrdersStoreContext>;
}

export function useWorkOrdersStore(): WorkOrdersStore {
  const store = use(WorkOrdersStoreContext);
  if (!store) throw new Error('useWorkOrdersStore must be used inside <WorkOrdersProvider>');
  return store;
}

WorkOrdersProvider is the counterpart of provideWorkOrders(). The shell layout mounts it (section 12.8), so the store exists exactly where the maintenance routes do. React 19 renders a context directly as a provider and reads it with use().

12.6. The facade hook

libs/maintenance/data-access/src/lib/use-work-orders.ts

'use client';

import { useQuery } from '@tanstack/react-query';
import { useStore } from 'zustand';
import { isOverdue, matchesFilter, type WorkOrder } from '@fleetline/maintenance/model';
import { toErrorMessage } from '@fleetline/shared/util-http';
import { useAssignWorkOrder } from './work-orders.mutations';
import { useWorkOrdersStore } from './work-orders.provider';
import { workOrdersQuery } from './work-orders.queries';

export function useWorkOrders(depotId: string) {
  const store = useWorkOrdersStore();
  const criteria = useStore(store, (state) => state.criteria);
  const filterChanged = useStore(store, (state) => state.filterChanged);
  const query = useQuery(workOrdersQuery(depotId));
  const assignment = useAssignWorkOrder(depotId);

  const all = query.data ?? [];
  const filter = { ...criteria, depotId };
  const failure = query.error ?? assignment.error;

  return {
    visible: all.filter((order) => matchesFilter(order, filter)),
    overdueCount: all.filter((order) => isOverdue(order, new Date())).length,
    filter,
    loading: query.isPending,
    error: failure ? toErrorMessage(failure) : null,
    filterBy: filterChanged,
    assign: (order: WorkOrder, assigneeId: string) => assignment.mutate({ id: order.id, assigneeId }),
  };
}

The hook has the same members as the Angular facade, except open(): the query is keyed by depotId, so there is nothing to open. The facade has no side effects. It registers nothing and sends nothing on mount, so any number of components can use it, for example an overdue counter in the header, without a second request.

Every store field has its own selector. In Zustand 5 a selector that returns a new object needs useShallow, otherwise rendering loops. visible and overdueCount are computed on every render; the React Compiler memoizes them automatically, so the facade needs neither useMemo nor useCallback.

libs/maintenance/data-access/src/index.ts

export { workOrdersQuery } from './lib/work-orders.queries';
export { WorkOrdersProvider } from './lib/work-orders.provider';
export { useWorkOrders } from './lib/use-work-orders';

Three exports. The Zustand store, the mutations and the HTTP client are private.

12.7. Feature, ui and route

The feature has two containers. WorkOrdersRoute is a server component: it loads the work orders through data-access-server, with the user's cookies, and hands them to the query cache through HydrationBoundary. WorkOrdersPage is a client component: it reads the facade and composes the ui libraries.

libs/maintenance/feature-work-orders/src/lib/work-orders-route.tsx

import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { workOrdersQuery } from '@fleetline/maintenance/data-access';
import { listWorkOrders } from '@fleetline/maintenance/data-access-server';
import { makeQueryClient } from '@fleetline/shared/data-access-query';
import { WorkOrdersPage } from './work-orders-page';

export async function WorkOrdersRoute({ depotId }: { depotId: string }) {
  const client = makeQueryClient();
  await client.prefetchQuery({ ...workOrdersQuery(depotId), queryFn: () => listWorkOrders(depotId) });

  return (
    <HydrationBoundary state={dehydrate(client)}>
      <WorkOrdersPage depotId={depotId} />
    </HydrationBoundary>
  );
}

libs/maintenance/data-access-server/src/lib/work-orders.ts

import 'server-only';
import { apiFetch } from '@fleetline/shared/data-access-server';
import type { WorkOrder } from '@fleetline/maintenance/model';

export function listWorkOrders(depotId: string): Promise<WorkOrder[]> {
  return apiFetch<WorkOrder[]>(`/depots/${depotId}/work-orders`);
}

The first render in the browser already has the data, with no second request and no spinner; the app's loading.tsx shows only while the server is fetching.

libs/maintenance/feature-work-orders/src/lib/work-orders-page.tsx

'use client';

import { useWorkOrders } from '@fleetline/maintenance/data-access';
import { StatusFilter, WorkOrderCard } from '@fleetline/maintenance/ui-work-order-card';
import { useVehicleSummaries } from '@fleetline/fleet/api';
import { EmptyState, Spinner } from '@fleetline/shared/ui-design-system';

export function WorkOrdersPage({ depotId }: { depotId: string }) {
  const workOrders = useWorkOrders(depotId);
  const vehicles = useVehicleSummaries(workOrders.visible.map((order) => order.vehicleId));

  return (
    <>
      <h1>
        Work orders <small>{workOrders.overdueCount} overdue</small>
      </h1>
      <StatusFilter
        status={workOrders.filter.status}
        query={workOrders.filter.query}
        onStatusChange={(status) => workOrders.filterBy({ status })}
        onQueryChange={(query) => workOrders.filterBy({ query })}
      />
      {workOrders.loading ? (
        <Spinner />
      ) : workOrders.visible.length === 0 ? (
        <EmptyState title="No work orders match this filter" />
      ) : (
        workOrders.visible.map((order) => (
          <WorkOrderCard
            key={order.id}
            workOrder={order}
            vehicleLabel={vehicles[order.vehicleId]?.plate ?? ''}
            onAssign={(assigneeId) => workOrders.assign(order, assigneeId)}
          />
        ))
      )}
    </>
  );
}

libs/maintenance/ui-work-order-card/src/lib/work-order-card.tsx

import { isOverdue, type WorkOrder } from '@fleetline/maintenance/model';
import { Badge, MechanicPicker } from '@fleetline/shared/ui-design-system';
import { formatRelative } from '@fleetline/shared/util-date';
import styles from './work-order-card.module.scss';

interface WorkOrderCardProps {
  workOrder: WorkOrder;
  vehicleLabel: string;
  onAssign: (assigneeId: string) => void;
}

export function WorkOrderCard({ workOrder, vehicleLabel, onAssign }: WorkOrderCardProps) {
  const overdue = isOverdue(workOrder, new Date());

  return (
    <article className={overdue ? `${styles.card} ${styles['card--overdue']}` : styles.card}>
      <header>
        <h3>{workOrder.title}</h3>
        <Badge tone={workOrder.priority === 'urgent' ? 'danger' : 'neutral'}>{workOrder.priority}</Badge>
      </header>
      <p className={styles.vehicle}>{vehicleLabel}</p>
      <p className={styles.due}>{formatRelative(workOrder.dueAt)}</p>
      <MechanicPicker depotId={workOrder.depotId} value={workOrder.assigneeId} onChange={onAssign} />
    </article>
  );
}

work-order-card.module.scss is the file from section 6.3. CSS Modules turn .card into a name that is unique across the whole application, so a class from one library cannot leak into another.

The route files in the application stay a few lines long.

apps/customer/app/maintenance/layout.tsx

import type { ReactNode } from 'react';
import { MaintenanceLayout } from '@fleetline/maintenance/feature-shell';

export default function Layout({ children }: { children: ReactNode }) {
  return <MaintenanceLayout>{children}</MaintenanceLayout>;
}

apps/customer/app/maintenance/depots/[depotId]/work-orders/page.tsx

import { WorkOrdersRoute } from '@fleetline/maintenance/feature-work-orders';

export default async function Page({ params }: { params: Promise<{ depotId: string }> }) {
  const { depotId } = await params;
  return <WorkOrdersRoute depotId={depotId} />;
}

12.8. The shell and another domain's API

The shell layout is a server component. It first checks the permission on the server, then mounts the domain's providers. In Angular, canActivate and providers on the route do this (section 11.3).

libs/maintenance/feature-shell/src/lib/maintenance-layout.tsx

import type { ReactNode } from 'react';
import { WorkOrdersProvider } from '@fleetline/maintenance/data-access';
import { VehicleSummaryProvider } from '@fleetline/fleet/api';
import { requirePermission } from '@fleetline/identity/api';

export async function MaintenanceLayout({ children }: { children: ReactNode }) {
  await requirePermission('maintenance:read');

  return (
    <VehicleSummaryProvider>
      <WorkOrdersProvider>{children}</WorkOrdersProvider>
    </VehicleSummaryProvider>
  );
}

A Next.js layout does not unmount on navigation between maintenance pages, so the stores survive navigation inside the domain and disappear when the planner leaves it.

useVehicleSummaries from fleet/api is the counterpart of VehicleSummaryStore from section 7.1, written in Zustand: maintenance passes a list of ids, and fleet loads the missing plates in one request.

libs/fleet/data-access/src/lib/vehicle-summary.store.ts

import { createStore } from 'zustand/vanilla';
import type { VehicleSummary } from '@fleetline/fleet/model';
import { toErrorMessage } from '@fleetline/shared/util-http';
import { fleetHttp } from './fleet.http';

export interface VehicleSummaryState {
  entities: Record<string, VehicleSummary>;
  ensureLoaded: (ids: readonly string[]) => Promise<void>;
}

export function createVehicleSummaryStore() {
  return createStore<VehicleSummaryState>()((set, get) => ({
    entities: {},
    ensureLoaded: async (ids) => {
      const missing = [...new Set(ids)].filter((id) => !get().entities[id]);
      if (missing.length === 0) return;
      try {
        const vehicles = await fleetHttp.summaries(missing);
        set((state) => ({
          entities: { ...state.entities, ...Object.fromEntries(vehicles.map((vehicle) => [vehicle.id, vehicle])) },
        }));
      } catch (error) {
        console.error('fleet summaries', toErrorMessage(error));
      }
    },
  }));
}

export type VehicleSummaryStore = ReturnType<typeof createVehicleSummaryStore>;

libs/fleet/data-access/src/lib/vehicle-summaries.tsx

'use client';

import { createContext, use, useEffect, useState, type ReactNode } from 'react';
import { useStore } from 'zustand';
import { createVehicleSummaryStore, type VehicleSummaryStore } from './vehicle-summary.store';

const VehicleSummaryContext = createContext<VehicleSummaryStore | null>(null);

export function VehicleSummaryProvider({ children }: { children: ReactNode }) {
  const [store] = useState(createVehicleSummaryStore);
  return <VehicleSummaryContext value={store}>{children}</VehicleSummaryContext>;
}

export function useVehicleSummaries(ids: readonly string[]) {
  const store = use(VehicleSummaryContext);
  if (!store) throw new Error('useVehicleSummaries must be used inside <VehicleSummaryProvider>');
  const entities = useStore(store, (state) => state.entities);
  const key = ids.join(',');

  useEffect(() => {
    void store.getState().ensureLoaded(key ? key.split(',') : []);
  }, [store, key]);

  return entities;
}

The effect depends on key, not on the array, because the feature creates a new array on every render.

libs/fleet/api/src/index.ts

export type { VehicleSummary, VehicleId } from '@fleetline/fleet/model';
export { VehicleSummaryProvider, useVehicleSummaries } from '@fleetline/fleet/data-access';
export { VehicleBadge } from '@fleetline/fleet/ui-vehicle-badge';

12.9. Pitfalls specific to Next.js

  • 'use client' is a boundary of its own. Put it in client components, providers and hooks, never in model, util, or the file with queryOptions that the server imports too.
  • No store in a module variable. Zustand's create() or new QueryClient() at module level shares state between all requests on the server. Stores and the query client are created in providers.
  • Zustand does not copy server data. The list from the API lives in the query cache; a copy of it in a store is a second source of truth.
  • Do not import a server library into a client file "just for the type". Types live in model.
  • Server actions belong to data-access-server. A feature imports them through data-access re-exports only if the lint tags allow it; otherwise the page passes them as props.
  • Route files stay thin. A page.tsx that grows logic is the Next.js version of a fat Angular app component.