ui-stack-react
Building interfaces in React 19: file layout by feature, typed function components, composition and slots, variants with cva, native props and refs passed through, where state lives and derived values, effects only for outside systems, keys, context split by concern, server data with TanStack Query, forms with actions or react-hook-form, Suspense and error boundaries, transitions and deferred values, portals and headless accessible primitives, the React Compiler and memo, Testing Library, and the traps (stale closures, racing effects, props copied into state, index keys, giant components). Read when the project uses React.
- License 许可
- Apache-2.0
- 所属仓库
- enowdev/enowxcli
- 最近更新
- 2026-10-06
- Stars
- ★ 67
- Forks
- 21
01 前言 Front Matter
- name
- ui-stack-react
- description
- Building interfaces in React 19: file layout by feature, typed function components, composition and slots, variants with cva, native props and refs passed through, where state lives and derived values, effects only for outside systems, keys, context split by concern, server data with TanStack Query, forms with actions or react-hook-form, Suspense and error boundaries, transitions and deferred values, portals and headless accessible primitives, the React Compiler and memo, Testing Library, and the traps (stale closures, racing effects, props copied into state, index keys, giant components). Read when the project uses React.
03 SKILL.md 正文
React
The generated React component is one 400-line file with a boolean prop per
variation, an effect that copies props into state and another that fetches,
key={index}, useMemo on everything, a clickable div, and one context
holding the whole app. This is React 19 (19.3 in September 2026) as
experienced teams write it: small typed components that compose, state where
it belongs, effects only at the edges. Next.js is in ui-stack-next;
app-wide state and data in frontend-state and frontend-data.
1. Project layout
src/main.tsx src/App.tsx entry, providers, router
src/routes/ one file per screen (or the router's layout)
src/components/ui/ primitives: Button, Input, Field, Dialog
src/features/orders/ OrderTable.tsx, OrderFilters.tsx, useOrders.ts,
orders.api.ts, OrderTable.test.tsx
src/lib/ the API client, formatting, cn
- Files by feature, not by kind: everything about orders sits together, and
removing a feature removes a folder. Primitives in
components/ui/, composed parts infeatures/<feature>/(orcomponents/<feature>/), or the project's own layout. - A new app: Vite (
npm create vite@latest app -- --template react-ts), a router (React Router or TanStack Router) and TanStack Query; Next.js when pages need server rendering or search traffic (ui-stack-next).
2. Components
- Function components, one per file named for it, props typed (a
typeorinterface); match the project's export style. - Composition over configuration:
childrenand named slots (icon,actionsprops that take elements) rather than a boolean per variation (showIcon,isCompact). Variants as avariantand asizeprop. - A primitive passes native props and the
refthrough, so it stays a real button to forms and screen readers. In 19refis an ordinary prop;forwardRefonly before 19.
import type { ComponentProps } from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/cn";
const button = cva(
"inline-flex items-center justify-center gap-2 rounded-md font-medium disabled:opacity-50",
{
variants: {
variant: { primary: "bg-accent text-on-accent", quiet: "text-ink hover:bg-surface-2" },
size: { sm: "h-8 px-3 text-sm", md: "h-10 px-4" },
},
defaultVariants: { variant: "primary", size: "md" },
},
);
type ButtonProps = ComponentProps<"button"> & VariantProps<typeof button>;
export function Button({ variant, size, className, type = "button", ...props }: ButtonProps) {
return <button type={type} className={cn(button({ variant, size }), className)} {...props} />;
}
type="button"by default: a button inside a form otherwise submits it. Without Tailwind, the same shape with a class map from a CSS Module.- Never define a component inside another's render: it remounts every time and loses its state and focus.
- A component past about 200 lines or doing two jobs splits: its data into a hook, each region into its own component.
3. State
- State in the lowest component that needs it; lift it when two need it; context for what many parts read (theme, the signed-in user), not for everything.
- Derive values during render instead of copying them into state and
syncing with an effect: a filtered list is
items.filter(...)in render. - State that should reset when a record changes:
key={record.id}on the component, not an effect that clears it. - Context split by concern (the user, the theme, one per compound
component), its value stable; in 19 the context is the provider
(
<ThemeContext value={theme}>). A value that changes often (form input, the pointer) re-renders every reader: keep it local, or in a store with selectors (Zustand,useSyncExternalStore). - Filters, tabs and the page number live in the URL through the router, so reload and share keep them.
4. Effects and events
- Effects only to synchronise with something outside React (a subscription, a socket, a third-party widget, the document title), with a cleanup. Strict Mode runs them twice in development to prove the cleanup.
- What a click causes belongs in the click handler, not in an effect watching state the handler set.
- An effect that needs the latest props without re-running reads them
through
useEffectEvent(19.2):
const onMessage = useEffectEvent((message: Message) => {
if (!muted) notify(message); // always the current `muted`
});
useEffect(() => {
const socket = connect(roomId);
socket.on("message", onMessage);
return () => socket.disconnect();
}, [roomId]); // reconnects only when the room changes
5. Server data
- Through the project's library (TanStack Query, SWR) or the framework's loaders; never a hand-written fetch in an effect when one of those is there. Loading, error and empty are three branches in the markup, each saying what to do:
const orders = useQuery({
queryKey: ["orders", filters],
queryFn: ({ signal }) => api.listOrders(filters, { signal }),
});
if (orders.isPending) return <OrdersSkeleton />;
if (orders.isError) return <LoadError what="orders" onRetry={() => orders.refetch()} />;
if (orders.data.length === 0) return <NoOrders />;
return <OrderTable orders={orders.data} />;
- The key holds every input, so a filter change refetches and caches;
after a mutation,
queryClient.invalidateQueries({ queryKey: ["orders"] }). - Without a library, a fetch in an effect aborts in its cleanup
(
AbortController), or the slower of two responses lands last and wins.
6. Lists and forms
- Keys are stable ids from the data, never the index for a list that changes: with index keys, row state and focus stay at the position while the data moves. Hundreds of rows are virtualised (TanStack Virtual) or paginated.
- Labels tied to fields with
htmlForand an id fromuseId; the error in words under the field witharia-describedby; the submit button disabled and showing progress while pending (frontend-forms). - Use the project's form library (react-hook-form, with zod when it is there) for large forms and validation as the user types:
const form = useForm<Invite>({ resolver: zodResolver(inviteSchema), defaultValues: { email: "" } });
const id = useId();
const error = form.formState.errors.email;
return (
<form onSubmit={form.handleSubmit(sendInvite)} noValidate>
<label htmlFor={id}>Work email</label>
<input id={id} type="email" autoComplete="email" {...form.register("email")}
aria-invalid={!!error} aria-describedby={`${id}-error`} />
<p id={`${id}-error`}>{error?.message}</p>
<button type="submit" disabled={form.formState.isSubmitting}>Send invite</button>
</form>
);
- A form that posts can use React 19 actions:
<form action={fn}>,useActionStatefor the result and a pending flag,useFormStatusin a child of the form,useOptimisticfor a list that updates at once. React resets an uncontrolled form after its action: on a failure, return the submitted values and use them asdefaultValue.
7. Suspense, errors and transitions
<Suspense fallback={<Skeleton />}>around the part that waits (a lazy component,use(promise), a suspense query), where the layout should hold, not around the whole app.- Error boundaries around regions that can fail alone (a chart, a panel),
with a retry:
react-error-boundary's<ErrorBoundary>, since a boundary is otherwise a class component (frontend-errors). useTransitionfor an update that renders a lot (a tab switch, a filter on a big table): the old screen stays usable andisPendingdims it.useDeferredValuefor a fast-typed value feeding something slow:<Results query={deferredQuery} dimmed={query !== deferredQuery} />.<Activity mode="hidden">(19.2) keeps a hidden tab's state and pauses its effects instead of unmounting it.
8. Accessibility and overlays
- Semantic elements, never a clickable
div. Dialogs, menus, tabs, popovers, tooltips and comboboxes from the project's primitives (Radix, Base UI, React Aria, or shadcn/ui built on one), which handle focus, keys and ARIA, rather than hand-rolled. - Overlays render in a portal (
createPortal(node, document.body), which the libraries do) or the native top layer (<dialog>,popover), so nooverflow: hiddenparent clips them and noz-indexwar starts. - Focus moves into a dialog and back to its trigger on close; after a route
change, focus goes to the new page's
h1(frontend-accessibility). <title>and<meta>rendered in a component are hoisted to<head>in 19: a title per screen without a helmet library.
9. Performance
- Memoise after measuring, not by habit. With the React Compiler (1.0) on,
components and values are memoised for you: add no
useMemo,useCallbackormemoby habit, and keep existing ones until a test shows they can go. - Turning the compiler on: with
@vitejs/plugin-react6, addbabel({ presets: [reactCompilerPreset()] })besidereact()(babelfrom@rolldown/plugin-babel, the preset from@vitejs/plugin-react); earlier versions takereact({ babel: { plugins: ["babel-plugin-react-compiler"] } }); Next.js hasreactCompiler: true. Its lint rules come with the latesteslint-plugin-react-hooks. - Split heavy routes and components with
lazyand a Suspense fallback; import one function, not a library's barrel. Images with sizes set (frontend-performance).
10. Testing
Behaviour as a user meets it: Vitest with Testing Library
(@testing-library/react, user-event, jest-dom), queries by role and
name, never by class or test id first (frontend-testing).
test("filters orders by status", async () => {
const user = userEvent.setup();
render(<Orders initial={orders} />);
await user.click(screen.getByRole("button", { name: "Paid" }));
expect(screen.getAllByRole("row")).toHaveLength(3); // the header and two paid
});
11. Traps
- Stale closures: an interval or handler reading state from the render that
made it. Use the updater (
setCount((c) => c + 1)), a ref, oruseEffectEvent. - Racing effects: two requests for two ids, the older landing last. Abort in the cleanup, or let the data library handle it.
- Props copied into state (
useState(props.user)) never update: derive, or reset withkey. {count && <Badge />}renders0: writecount > 0 &&.- Ten
useStates that change together: oneuseReducer, or split the component. - Prop drilling answered with a context for everything: pass
childrenand elements instead, so the middle layers never see the data.
Check it
npm run build(a Vite template runstsc -b && vite build),npm run lintwhen there is one,npx vitest run.- With Vite, look at the result with the
previewtool:urlhttp://localhost:5173/andstartnpm run dev -- --port 5173 --strictPort. With Next, seeui-stack-next. - The console in the
previewreport: key warnings, hydration errors and failed requests are bugs, not noise.
Avoid
A boolean prop per variation; components defined inside components; state
copied from props; effects for derived values or for events; fetch in an
effect beside a data library; index keys on changing lists; useMemo by
habit; a context for everything; a clickable div; a hand-rolled dialog,
menu or combobox; overlays clipped by a parent; {count && ...}.
04 同仓库更多 Skills
demo-skill
Project-scope demo skill for tests.
writing
Writing words people read: the specific thing instead of claims, words to drop, sentences, interface copy (buttons, labels, errors, empty states, confirmations), page copy, notifications and emails, alt text and link text, numbers and dates, words that translate well, documentation and voice. Read before writing a page's copy, an interface's text or a document.
ui
Designing or restyling an interface: direction, layout, type, colour, icons, components, states, responsive behaviour. Read before building a page, a screen or a set of components.
ui-themes
Light and dark themes, and colour that holds in both: tokens with a value per theme, and what each kind of content needs to stay visible (icons, SVG drawings and line art, logos, photos, screenshots, charts, code, maps, borders, shadows, focus, form controls), switching without a flash, and checking both. Read before building a second theme or a theme toggle, and before any drawing, logo or chart on a page that has two themes.
ui-structure
Structure before styling: the blueprint written before any interface code (the screen's job, the regions its kind of page needs, their order and why, the layout skeleton in numbers, the components and their states), the anatomy and order of a homepage, a dashboard, a list, a detail page, settings, a form, sign-in, pricing, docs, an article and a checkout, and how to turn the blueprint into code (tokens, layout primitives, components, sections, page). Read first, before building or rebuilding any page or screen.
ui-stack-vue
Building interfaces in Vue 3 and Nuxt: project layout, script setup with typed defineProps, defineEmits and defineModel, attribute fallthrough, slots and scoped slots, template refs, ref, reactive and computed, watch versus watchEffect, composables and VueUse, provide and inject, Pinia, keyed v-for, transitions, Nuxt 4 (app directory, pages, layouts, useFetch and useAsyncData keys, $fetch in handlers, server routes, runtime config, useSeoMeta, NuxtImg, middleware), VeeValidate forms, Reka UI and Nuxt UI, testing, vue-tsc, and the traps. Read when the project uses Vue or Nuxt.