api-shape
The shape of what others build on: parts that are composed, logic that is written out.
When an agent loads it
Shapes the API of code that others build on: a shared component, a family of components, a hook or a small library. It follows two models: shadcn's modular parts (small units the caller composes, one folder each, code that lives in the project) and TanStack's written-out logic (no markup, one object of named options, features that are registered, state the caller can read and own). Use when creating or changing a shared component, hook, utility or library, or a registry of them; when a component collects props like title, icon, actionLabel or showFooter, or booleans that can contradict each other; when logic and markup are welded together; when a caller can't read or set a piece of state; when arguments are passed by position; before publishing a package.
Install
npx skills add simon-lund/skills --skill api-shape The skills CLI puts it where your agent reads
skills: Claude Code, Codex, Cursor and the others it knows. npx skills update brings
in a later version.
Clone the repository:
git clone https://github.com/simon-lund/skills.gitCopy the skill's folder to where your agent reads skills. For Claude Code:
cp -r skills/skills/api-shape ~/.claude/skills/The folder holds 3 files:
SKILL.md,references/modular.md,references/written-out.md.
Why it exists
The moment a piece of code is used by someone other than its author, its shape is a promise. An agent left alone gives it the wrong one: a component with a prop for every idea, and logic that does things nobody asked for.
This skill takes two libraries as its models. It decides six things before any code, then checks the result from the side of whoever will call it.
Where it came from
- 10 October 2026: my component library began as a registry on shadcn-svelte. Its brief for agents says "Composition, not configuration", and "Prop creep is the smell that a part is missing". Its data table stands on TanStack's table core.
- 27 November 2026: I called shadcn and TanStack "the libs with the best APIs I have seen in the wild", shadcn "for its nice modularization", TanStack "for its verbosity".
Those two words are the skill's two halves. How it reads the second one is the skill's reading, and wider than the word: the caller writes out what it uses, and nothing happens that the call site doesn't show. It takes in two things that stand beside that in TanStack: logic without markup, and state with one owner.
Don't add a prop for every idea. The tenth idea is a tenth prop, and none of them can go where the caller needs it.
Do give each place its own part. The next idea is something the caller puts in, and the card doesn't change.
What exists already
My own rule asks for a reason before I build what others have built. This is what I found:
- components.build, by Hayden Bleasel and shadcn: a specification for building components, with a skill of its own. It is the long form of this skill's first half, in React.
- vercel-composition-patterns: eight rules for React, the first of them against boolean props that switch behaviour.
- shadcn and shadcn-svelte, and the skills TanStack Table and Router ship inside their npm packages: how to use those libraries.
- codebase-design by Matt Pocock, on deep modules in general, and library-api-design by Toss, on the public API of a React library.
Why this one anyway: none of them puts the two models side by side, with one decision about which applies. For the second half, logic that is written out, I found no skill that takes it as a model to build by. None has Svelte 5 beside React. And this one sends an agent to the others first.
The rules behind it
Do build on primitives that exist before writing new markup; extract a new primitive when one is missing. Generic parts are composed (parts, variants, slots), never configured with a growing list of props. (The composition model of shadcn/ui and Radix.)
Don't turn something down because it wasn't made here. Before building a library, a service, a tool or a method of my own, look for one that exists and holds up; use it and credit it. Building my own needs a written reason. (The not-invented-here syndrome: in Ralph Katz and Thomas Allen's 1982 study of 50 R&D teams, teams that had stayed together for years looked outside less and did worse.) A default, not a law: what the product is for, the part that is actually new, is mine to build and own, even when something off the shelf comes close (Joel Spolsky, "In Defense of Not-Invented-Here Syndrome").
Don't change what current callers rely on. Add opt-in behaviour, move callers deliberately, then pin the contract with tests. (Hyrum's law: with enough users, every observable behaviour is depended on by somebody.)
Do keep one vocabulary for acts: the same word for the same thing, everywhere. (Nielsen: consistency and standards.)
Do make every API error carry a stable code next to its text; interfaces branch on the code, never on the prose.
Do start small and grow what works. (Gall's law: a complex system that works evolved from a simple system that worked.)
How to tell it works
- Before any code it says what exists already, and whether the thing is seen, logic or both.
- It writes the call site first, as it will stand in the doc.
- A badge beside the title, or a second action, goes in without a change to the component.
- Every piece of state can be read from outside, and has one owner.
- A wrong column or a wrong kind fails to compile where it is written.
- The logic's tests run without rendering anything.
The skill
API shape: what others build on
The moment a piece of code is used by someone other than its author (another screen, another person, another agent), its shape is a promise. Two families of libraries are this skill's models for that shape: shadcn/ui and shadcn-svelte for how a thing is cut into modules, and TanStack for how much of it is written out at the call site.
An agent left alone builds the opposite: one component with a prop for every idea, and logic that does things nobody asked for. So don't invent a shape. Decide six things, follow the two models, and check the result from the caller's side. Write each answer down.
First look at what exists. The project's own part comes before a new one. A library that
already does it comes before your own: where the project builds on shadcn, on Base UI, Radix or
Bits UI, or on TanStack, use that, and load that library's own skill (shadcn, shadcn-svelte,
the skills TanStack Table and Router ship inside their npm packages). This skill is for the part
that is yours to build.
Then say how far it reaches. A generic part (a button, a field, a dialog) is shared from its first use: it is never written out at the one place that needed it. A part that belongs to one feature stays beside that feature until a second place needs it.
1. Decide before any code
Seen, logic, or both
| Seen only | Logic only | Both | |
|---|---|---|---|
| Such as | a card, a badge, a row, a toolbar | choosing rows, the steps of a flow, a request and its cache | a data table, a combobox, a date picker |
| Its shape | parts the caller composes (section 2) | a core that renders nothing (section 3) | two layers: the core, and parts that render what it works out |
A thing that is both is never one component with a prop for each feature.
What the caller writes out
List what the unit would decide by itself: its features, its defaults, where its data comes from. For each, the caller either writes it at the call site or can read there that it was left to the default. Nothing happens that the call site doesn't show.
Who owns each piece of state
Name the pieces: what is open, what is chosen, the order, the page. Each has one owner, and the caller chooses it: the unit (it may be told where to start), or the caller (it gives the current value and is told every change). Every piece can be read from outside, whoever owns it.
The closed sets
What comes in a few fixed kinds is one prop with a closed list of values: variant, size. One
prop per question, and never two booleans that can both be true. Everything else the caller puts
in as children. A kind is named after how it looks or how heavy it is, not after what it means in
one app: overdue belongs to the app's own wrapper around the part.
Who says the words
A generic part has a few words of its own: Close, Previous, "No results". Either the part says them itself, from its own place in the translations, or it has none and the caller passes every one. Choose once for the whole library. Mixed, some words are forgotten and some can't be changed.
What is promised
- One word per thing. The names of the library the project builds on are the names here:
value,defaultValueandonValueChangebeside Bits UI or Radix;state,initialStateandon…Changebeside TanStack. A callback of your own never reuses the name of a DOM event. - What callers already see stays. A new behaviour is a new option that callers choose. A default that changes breaks everyone who relied on it.
- An error has a name that code can branch on, beside its sentence.
- Tests hold the promise: one per thing a caller may rely on.
2. Modular: the shadcn model
references/modular.md has the model in shadcn's own terms, the checked code in React and in
Svelte 5, and the traps of this half. The long form of this half is components.build, by Hayden
Bleasel and shadcn, with its skill building-components. In short:
- A part is one element. It takes that element's own props, merges the caller's class last, passes everything else through and gives its element to whoever asks for it.
- A family is several parts the caller arranges: a root, and a part for each place something can go. No part switches another one on or off.
- Each part names itself on its element (
data-slot), and says its kind and its state there too (data-variant,data-state), so it can be styled from outside without a prop for it. - One folder per unit, with an index that exports its parts and its kinds. A unit can be taken alone, and its code lives in the project that uses it.
- Behaviour comes from a primitive underneath (Base UI, Radix, Bits UI). A part styles and names; it writes no focus handling of its own.
- The root's doc shows the family composed, once, as the caller would write it.
3. Written out: the TanStack model
references/written-out.md has the model in the words of TanStack's own packages, a unit of
logic built the same way with its tests, and the traps of this half. In short:
- The core renders nothing. It returns state, questions and acts. The markup is the caller's.
- One argument: an object with named keys. Also for the options of a single act.
- A feature is something the caller passes. What isn't passed doesn't exist: no method, no state, no type, no code in the bundle.
- One owner per piece of state, as decided above; a change is a value or a function of the value before.
- Types follow from what was written. The caller fills in no type by hand, and a wrong name fails to compile.
- The core knows no framework. An adapter of a few lines holds the state the framework's way.
- The short form is the app's. Where the long form repeats, the app fixes its own defaults once in its own code. The library stays written out.
4. The traps
Check each on the code. Each is a yes or a finding.
- A prop per idea:
title,icon,actionLabel,onAction,showFooter. A part is missing. - Booleans that can contradict:
primaryanddanger,compactandlarge. - A part that swallows its element: no
class, no other attribute, no way to its element. - Styling through props:
titleClassName,iconColor, where a name on the part would do. - A wrapper around a wrapper that passes on half of what the library under it takes.
- An app's meaning in a generic part:
variant="overdue". - A unit that can't be taken alone, or five units in one file.
- Logic welded to markup:
<DataTable sortable filterable paginated />. - State nobody can reach, or one value kept in two places.
- Arguments by position, and a bare
trueamong them. - Things that happen unasked: a feature that is on unless switched off, a setting read from a global, work done because a file was imported.
- Types the caller has to write, or
anyat the edge. - The framework inside the core.
- Two words for one thing:
open,isOpenandvisible;onChangeandonValueChange. - A default changed under its callers.
- No example of the whole, composed as a caller would write it.
5. Check it from the caller's side
- Write the call site first, before the unit: the example that will stand in its doc. If it reads badly, the shape is wrong.
- The next idea: put a badge beside the title, a second action in the header, a link where the title's text is. None of them touches the unit.
- Every piece of state: read it from outside, set it, reset it, and refuse a change.
- Leave a feature out and build: its code is gone from the bundle.
- A wrong name (a column, a kind, a key) fails to compile at the call site, and the right one needed no type written by hand.
- Count the props of each part. More than its element's own, its kinds and its state means a part is missing.
- Run the logic without rendering anything: its tests need no framework.
6. Report
- What existed already, and why this is built anyway.
- Seen, logic or both, and the layers that follow.
- The pieces of state, each with its owner.
- The kinds, and who says the words.
- The call site, as a caller writes it.
- The traps that failed and what was changed.
- What is promised to callers, and which test holds each promise.
references/modular.md Show Close
Modular: the shadcn model
How shadcn/ui and shadcn-svelte cut what is seen into modules, and how to build a part of your own the same way. The code here was type-checked on 27 November 2026 against React 19.3 with class-variance-authority 0.7, and Svelte 5.59 with tailwind-variants 4.0. The Svelte parts were also mounted in jsdom; the React parts were compiled, not run.
What the model is
shadcn/ui says of itself that it is not a component library but a way to build your own. Its documentation names five things it stands on; the first three are what "modular" means here.
- Open code. The source of a component goes into the project, and is changed there. The reason it gives: with an installed library, the first thing it doesn't do leads to wrapping its components, overriding its styles, or mixing in a second library.
- Composition. Every component has the same kind of interface: parts the caller arranges.
The card is seven separate functions (
Card,CardHeader,CardTitle,CardDescription,CardAction,CardContent,CardFooter), the dialog ten. - Distribution. A unit is described by a small file (
registry-item.json: its files, what it depends on, which other units it needs), and a command line tool places it. Units are taken one at a time.
How a part is written, in the current source of both libraries:
- One element, with that element's props.
React.ComponentProps<"div">with the rest spread onto the element; in shadcn-svelte...restPropsandref = $bindable(null). NoforwardRefsince February 2025: in React 19refis a prop. - A name on every part. Since February 2025 every part carries
data-slot, so it can be styled from its parent. - Kinds as a closed list:
class-variance-authority(cva:variants,defaultVariants,compoundVariants) in React,tailwind-variants(tv) in shadcn-svelte. - Classes merged by one helper,
cn(), with the caller's class last. Since September 2026 both libraries take it from the packagecn; the helper written out below is the same thing. - Behaviour comes from a primitive underneath. A part styles and names; it doesn't write its own focus handling. shadcn/ui stands on Base UI by default since July 2026, with Radix and React Aria as the other bases; shadcn-svelte stands on Bits UI.
- A part can lend itself to another element, and how is the primitive's:
asChildon Radix, arenderprop on Base UI, achildsnippet on Bits UI. For a link that looks like a button, shadcn's page for its Base UI button says to put the button's kinds (buttonVariants) on the link. - State starts inside and can be owned from outside:
open,defaultOpenandonOpenChange;value,defaultValueandonValueChange.
The full specification of this half exists: components.build, by Hayden Bleasel and shadcn,
with its own skill (building-components). Its examples are in React. Read it for the long
form; what follows is the short one, with Svelte 5 beside React.
The same card, twice
A prop for every idea:
import type { ReactNode } from 'react';
// Don't: one component, and a prop for every idea anyone has had about it.
interface CardProps {
title: string;
subtitle?: string;
icon?: ReactNode;
actionLabel?: string;
onAction?: () => void;
showFooter?: boolean;
footerText?: string;
compact?: boolean;
danger?: boolean;
}
export function Card({ title, subtitle, icon, actionLabel, onAction, showFooter, footerText, compact, danger }: CardProps) {
return (
<div className={`card ${compact ? 'card-compact' : ''} ${danger ? 'card-danger' : ''}`}>
<div className="card-header">
{icon}
<h3>{title}</h3>
{subtitle && <p>{subtitle}</p>}
{actionLabel && <button onClick={onAction}>{actionLabel}</button>}
</div>
{showFooter && <div className="card-footer">{footerText}</div>}
</div>
);
}
// The next idea (a badge beside the title, a second action, a link as the title) is a new prop.
export const usage = <Card title="Invoice 1042" subtitle="Northlight Studio" actionLabel="Open" onAction={() => {}} showFooter footerText="Due 8 Dec" />;
A part for every place:
import type { ComponentProps } from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from './cn.js';
// Do: every part is its own small component. It is one element, takes that element's own props,
// merges the caller's class last, and names itself for styling from outside.
export const cardVariants = cva('flex flex-col gap-4 rounded-xl border p-6', {
variants: {
// a closed set: one prop per question, never two booleans that can both be true
variant: { default: 'bg-card', sunk: 'bg-muted' },
size: { default: 'p-6', compact: 'p-3' }
},
defaultVariants: { variant: 'default', size: 'default' }
});
export function Card({ className, variant, size, ...props }: ComponentProps<'div'> & VariantProps<typeof cardVariants>) {
return <div data-slot="card" data-variant={variant ?? 'default'} className={cn(cardVariants({ variant, size }), className)} {...props} />;
}
export function CardHeader({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="card-header" className={cn('flex items-start gap-2', className)} {...props} />;
}
export function CardTitle({ className, ...props }: ComponentProps<'h3'>) {
return <h3 data-slot="card-title" className={cn('font-semibold leading-none', className)} {...props} />;
}
export function CardDescription({ className, ...props }: ComponentProps<'p'>) {
return <p data-slot="card-description" className={cn('text-muted-foreground text-sm', className)} {...props} />;
}
export function CardAction({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="card-action" className={cn('ms-auto', className)} {...props} />;
}
export function CardFooter({ className, ...props }: ComponentProps<'div'>) {
return <div data-slot="card-footer" className={cn('flex items-center', className)} {...props} />;
}
// The next idea needs no new prop: the caller puts it where it belongs.
export const usage = (
<Card size="compact" aria-labelledby="invoice-1042">
<CardHeader>
<CardTitle id="invoice-1042">
<a href="/invoices/1042">Invoice 1042</a>
</CardTitle>
<CardDescription>Northlight Studio</CardDescription>
<CardAction>
<button type="button">Open</button>
</CardAction>
</CardHeader>
<CardFooter>Due 8 Dec</CardFooter>
</Card>
);
The helper both import, written out:
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
/** Classes merged, the later one winning: the caller's `class` goes last. */
export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs));
In Svelte 5 a part looks the same. The root, with its kinds:
<script lang="ts" module>
import { tv, type VariantProps } from 'tailwind-variants';
export const cardVariants = tv({
base: 'flex flex-col gap-4 rounded-xl border',
variants: {
variant: { default: 'bg-card', sunk: 'bg-muted' },
size: { default: 'p-6', compact: 'p-3' }
},
defaultVariants: { variant: 'default', size: 'default' }
});
export type CardVariants = VariantProps<typeof cardVariants>;
</script>
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements';
import { cn } from './cn.js';
let {
ref = $bindable(null),
class: className,
variant = 'default',
size = 'default',
children,
...restProps
}: HTMLAttributes<HTMLDivElement> & CardVariants & { ref?: HTMLDivElement | null } = $props();
</script>
<div
bind:this={ref}
data-slot="card"
data-variant={variant}
class={cn(cardVariants({ variant, size }), className)}
{...restProps}
>
{@render children?.()}
</div>
One of its parts:
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements';
import { cn } from './cn.js';
let {
ref = $bindable(null),
class: className,
children,
...restProps
}: HTMLAttributes<HTMLHeadingElement> & { ref?: HTMLHeadingElement | null } = $props();
</script>
<h3 bind:this={ref} data-slot="card-title" class={cn('leading-none font-semibold', className)} {...restProps}>
{@render children?.()}
</h3>
And the folder's index, which gives each part a short name for Card.Title and a full one for
a single import:
import Root from './card.svelte';
import Title from './card-title.svelte';
export { Root, Title, Root as Card, Title as CardTitle };
The rules a part follows
- A part is one element. Its props are that element's own (
ComponentProps<'div'>,HTMLAttributes<HTMLDivElement>) and its kinds, nothing else. - The caller's class goes last in the merge, so the caller wins.
- Everything else passes through to the element:
id,aria-*,data-*, events. - The element can be reached:
refis a prop in React 19, andbind:refin Svelte. - It names itself:
data-slotsays which part it is,data-variantwhich kind. State stands on the element too (data-state,aria-expanded), so a style from outside needs no prop. - Kinds are a closed list with a default. A wrong one fails to compile: in the check for
this file,
variant="overdue"was refused in React andsize="huge"in Svelte. - A part that needs the root's kind reads it from the root (a context, or a selector on the
root's
data-variant), never from a prop of its own that could disagree. - Content is children. No
title="…", noitems={[…]}, no prop that switches another part on. - One folder per unit, with an index. What it imports from outside its folder is short and named: the class helper, the primitive under it.
- Its kinds are exported beside the part (
cardVariants), so their look can be put on another element without a prop for it. - The root's doc comment shows the family composed, as a caller writes it.
When parts are too much
Parts have a price: every invoice card in an app writes the same six lines. The answer is not a
shorter part. The library stays in parts, and the app writes its own short form once: a wrapper
that knows what an invoice is, takes invoice as its one prop and composes the parts with the
app's own words. A prop like that is right there and wrong in the library. It is the same answer
as in written-out.md: the library is long, and the short form is the app's.
The traps of this half
A prop per idea
- You see:
title,subtitle,icon,actionLabel,onAction,showFooter. Each new screen adds one, and still can't put a badge beside the title. - Why: the component decides where everything goes, so every wish has to pass through it.
- Fix: a part for each place something can go. The caller puts things there.
Booleans that can contradict
- You see:
<Button primary danger>,<Card compact large>, and code inside that decides which one wins. - Fix: one prop per question, with a closed list of answers:
variant,size.
A part that swallows its element
- You see: a class from the caller that has no effect, an
aria-labelthat never reaches the element, arefthat is null. - Fix: rules 2 to 4.
Styling through props
- You see:
titleClassName,iconColor,headerPadding: a prop for every style someone needed once. - Fix: the part names itself and its state on its element, and takes a class. The caller
styles
[data-slot=card-title]or passes a class to the part itself.
A wrapper around a wrapper
- You see:
MyDialogaround the library's dialog, passing on eight of its thirty props. The ninth is needed next week. - Fix: where the code is the project's own, change it there. Where it isn't, use it directly, and wrap only to say what something means in the app (the short form above).
An app's meaning in a generic part
- You see:
variant="overdue",tone="premium", aninvoiceprop on a card that should serve any content. - Fix: the part's kinds are named after how they look or how heavy they are. What a look means in this app is said by the app's wrapper.
A unit that can't be taken alone
- You see: to use the date picker, five other folders have to come too, or one file holds four families.
- Fix: one folder per unit, and a short, named list of what it needs from outside.
Sources
- shadcn/ui, "Introduction" (ui.shadcn.com/docs): not a component library; Open Code, Composition, Distribution, Beautiful Defaults, AI-Ready. "registry-item.json" in its registry docs.
- shadcn/ui changelog: "February 2025 - Tailwind v4" (
data-sloton every primitive, noforwardRef), "July 2026 - Base UI as the Default", "September 2026 - cn". Component source read at CLI version 4.23. - shadcn-svelte 1.8, docs and source: built on Bits UI; a folder imported as a namespace
(
Dialog.Root), its index with short and full names;tv,cn,...restProps,ref. - Bits UI, "Child Snippet". Base UI, "Composition" (the
renderprop). Radix Primitives, "Composition" (asChild), and its Dialog and Accordion references for the state props. - class-variance-authority 0.7, "Variants" and "API Reference".
- components.build, Hayden Bleasel and shadcn: Composition, Types, Data Attributes, State, Styling, asChild.
- Vercel, skill
vercel-composition-patterns(January 2026): eight rules for React, the first of them against boolean props that switch behaviour. - Kent C. Dodds, "React Hooks: Compound Components" (2019); he credits Ryan Florence with the pattern. Ariya Hidayat, "The Pitfalls of Boolean Trap" (2011).
- React, "Sharing State Between Components": controlled and uncontrolled. Svelte, "$bindable".
references/written-out.md Show Close
Written out: the TanStack model
How TanStack shapes logic that others build on, in the words of its own packages, and how to
build a unit of your own the same way. The code here was type-checked on 27 November 2026 against
@tanstack/react-table 9.3.1, @tanstack/react-query 5.108.4, React 19.3 and Svelte 5.59. The
selection example ran its assertions in Node 24, and the Svelte example was mounted and clicked
through in jsdom. The React table was compiled, not run.
What the model is
TanStack's own word for it is "explicit": one of its four product tenets is headed
Predictable, Explicit, Type-Safe Behavior, and rules out hidden global state. TanStack Table 9
ships its own skill inside its npm package (node_modules/@tanstack/table-core/skills/); what
follows is taken from there, from the package's types and from the docs.
- It renders nothing. The table works out state and rows. The markup, its meaning, its styles and what happens on a click belong to whoever renders it. The docs call this headless, and give the reason: state, events and the processing of data are the hard part, and kept apart they can be used under any look.
- A feature exists once it is registered.
tableFeatures({ … })lists what this table can do. Sorting that isn't in the list has no method, no state and no code in the bundle. The set of all features exists too, and the package names it for what it is: a convenience with a bundle's cost. Measured with esbuild 0.28, minified: a table with no optional feature is 25 kB, with sorting 32 kB, with every feature 95 kB. - Every piece of state has one owner, and the caller chooses it among three. Left alone,
the table owns a piece, and
initialStatesays where it starts. Or the framework's state owns it: the current value instate, and a callback that is told what it should become. Or a store of the caller's own does (atoms), which the docs prefer. Whoever owns it, it can be read from outside. - Types follow from what was written. The columns and the list of features are written once; the type of every cell, every option and every piece of state comes from them. The caller fills in no type by hand. A feature that isn't registered is gone from the types too.
- The core knows no framework.
@tanstack/table-corebuilds a table from plain values. An adapter (@tanstack/react-table,@tanstack/svelte-table, eight more) is the thin part that joins the table's state to the framework's own.
import { useState } from 'react';
import {
createColumnHelper,
createSortedRowModel,
rowSortingFeature,
sortFn_alphanumeric,
tableFeatures,
useTable,
type SortingState
} from '@tanstack/react-table';
type Invoice = { id: string; customer: string; amount: number };
// Everything the table can do is written here. What isn't registered doesn't exist: no method,
// no state, no code in the bundle.
const features = tableFeatures({
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
sortFns: { alphanumeric: sortFn_alphanumeric }
});
// The columns are written out once; every cell's type follows from them.
const helper = createColumnHelper<typeof features, Invoice>();
const columns = helper.columns([
helper.accessor('customer', { header: 'Customer' }),
helper.accessor('amount', { header: 'Amount, €' })
]);
export function Invoices({ data }: { data: Invoice[] }) {
// The caller owns this piece of state: it can put it in the address, or reset it.
const [sorting, setSorting] = useState<SortingState>([{ id: 'amount', desc: true }]);
const table = useTable({ features, columns, data, getRowId: (row) => row.id, state: { sorting }, onSortingChange: setSorting });
// The library renders nothing. The markup, its meaning and its styles are the caller's.
return (
<table>
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getAllCells().map((cell) => (
<td key={cell.id}>
<table.FlexRender cell={cell} />
</td>
))}
</tr>
))}
</tbody>
</table>
);
}
In TanStack Query the same hand shows in the call. Since version 5 every call takes one object
with named keys; the forms with arguments by position were removed, because they were hard to
keep right in the types. The key names every variable the request depends on. queryOptions
does nothing when it runs: it exists so that the types follow from one definition.
import { queryOptions } from '@tanstack/react-query';
type Invoice = { id: string; customer: string; amount: number };
declare function fetchInvoice(id: string): Promise<Invoice>;
// One object with named keys. The key names everything the function depends on, written out.
export const invoiceQuery = (id: string) =>
queryOptions({
queryKey: ['invoices', id],
queryFn: () => fetchInvoice(id),
staleTime: 60_000
});
That is what "verbose" buys. The call site is longer, and everything that happens can be read there.
Build like it
A unit of logic of your own, in the same shape: choosing several rows of a list. It is the
logic of select.js in the skill lists-and-tables, without a document to act on.
/** Which rows are chosen: their ids. */
export type SelectionState = ReadonlySet<string>;
/** A new value, or a function from the value before to the new one. */
export type Updater<T> = T | ((previous: T) => T);
export interface SelectionOptions {
/** The ids that can be chosen, in the order they show. Read on every call, never copied. */
ids: () => readonly string[];
/** Where it starts, while the selection owns its state. */
initialState?: SelectionState;
/** The caller owns the state: this returns its current value. Give `onStateChange` with it. */
state?: () => SelectionState;
/** Told every new value. With `state`, the caller stores it; without, it only listens. */
onStateChange?: (next: SelectionState) => void;
}
/**
* Choosing several of a set of rows. Logic only: it renders nothing, knows no framework and
* holds no state the caller can't read, set or own.
*/
export function createSelection(options: SelectionOptions) {
let own: SelectionState = options.initialState ?? new Set();
/** The row a range starts from: the last one toggled. */
let anchor: string | null = null;
const getState = (): SelectionState => (options.state ? options.state() : own);
function setState(updater: Updater<SelectionState>) {
const next = typeof updater === 'function' ? updater(getState()) : updater;
if (!options.state) own = next;
options.onStateChange?.(next);
}
return {
getState,
setState,
isSelected: (id: string) => getState().has(id),
/** Of the rows that show: are all chosen, some, or none? */
getAllState(): 'all' | 'some' | 'none' {
const ids = options.ids();
const chosen = ids.filter((id) => getState().has(id)).length;
return chosen === 0 ? 'none' : chosen === ids.length ? 'all' : 'some';
},
/** One row. With `range`, every row from the last one toggled to this one takes its new state. */
toggle(id: string, { range = false }: { range?: boolean } = {}) {
const ids = options.ids();
const select = !getState().has(id);
const from = range && anchor !== null ? ids.indexOf(anchor) : -1;
const to = ids.indexOf(id);
const span = from === -1 || to === -1 ? [id] : ids.slice(Math.min(from, to), Math.max(from, to) + 1);
setState((previous) => {
const next = new Set(previous);
for (const each of span) select ? next.add(each) : next.delete(each);
return next;
});
anchor = id;
},
/** All rows that show, or none of them if all were chosen. */
toggleAll() {
const ids = options.ids();
const all = ids.every((id) => getState().has(id));
setState((previous) => {
const next = new Set(previous);
for (const id of ids) all ? next.delete(id) : next.add(id);
return next;
});
},
clear() {
anchor = null;
setState(new Set());
}
};
}
export type Selection = ReturnType<typeof createSelection>;
The rules it follows:
- It returns state, questions and acts.
getState, thenisSelectedandgetAllState, thentoggle,toggleAllandclear. No element, no class, no event listener. - One argument, an object with named keys. A second argument is an object too:
toggle(id, { range: true })says whattoggle(id, true)hides. - One owner per piece of state. Without
statethe unit keeps it andinitialStatesays where it starts. WithstateandonStateChangethe caller keeps it, and can store it in the address, reset it, or refuse a change.getState()reads it in both cases. - A change is a value or a function of the value before, so two changes in a row don't lose each other.
- What it needs is handed in. The ids come through
ids, read on every call. Nothing is looked up in a global, and nothing happens because a file was imported. - A feature is something the caller passes. What is left out of the options is left out of the bundle. A flag that switches a built-in feature off still ships the feature.
- Its types need no help.
ReturnType<typeof createSelection>is the whole type; the caller writes no generic.
Its test needs no framework and renders nothing. Node 24 runs the file as it stands
(node selection.test.ts), which is why it names its neighbour with .ts:
import assert from 'node:assert/strict';
import { createSelection, type SelectionState } from './selection.ts';
const ids = ['a', 'b', 'c', 'd', 'e'];
// the selection owns its state
const own = createSelection({ ids: () => ids });
assert.equal(own.getAllState(), 'none');
own.toggle('b');
assert.deepEqual([...own.getState()], ['b']);
assert.equal(own.getAllState(), 'some');
own.toggle('d', { range: true });
assert.deepEqual([...own.getState()].sort(), ['b', 'c', 'd']);
own.toggle('b', { range: true }); // back to b: the range b to d takes b's new state, unchosen
assert.deepEqual([...own.getState()], []);
own.toggleAll();
assert.equal(own.getAllState(), 'all');
own.toggleAll();
assert.equal(own.getAllState(), 'none');
// the caller owns the state
let held: SelectionState = new Set(['a']);
const seen: number[] = [];
const controlled = createSelection({ ids: () => ids, state: () => held, onStateChange: (next) => { held = next; seen.push(next.size); } });
controlled.toggle('c');
assert.deepEqual([...held].sort(), ['a', 'c']);
held = new Set(); // the caller changes it from outside
assert.equal(controlled.isSelected('a'), false);
controlled.clear();
assert.deepEqual(seen, [2, 0]);
// a caller that only listens and refuses the change: the state stays the caller's
let fixed: SelectionState = new Set(['a']);
const refused = createSelection({ ids: () => ids, state: () => fixed, onStateChange: () => {} });
refused.toggle('b');
assert.deepEqual([...refused.getState()], ['a']);
console.log('selection: all assertions pass');
The adapter is the few lines that hold the state the framework's way. In Svelte 5:
import { createSelection, type SelectionState } from './selection.js';
/** The same logic, with its state held the way Svelte holds state. */
export function useSelection(ids: () => readonly string[]) {
let state = $state.raw<SelectionState>(new Set());
return createSelection({ ids, state: () => state, onStateChange: (next) => (state = next) });
}
And where it is used, the markup is the caller's, built from parts (see modular.md):
<script lang="ts">
import * as Card from './index.js';
import { useSelection } from './selection.svelte.js';
let { rows }: { rows: { id: string; name: string }[] } = $props();
const selection = useSelection(() => rows.map((row) => row.id));
</script>
<Card.Root size="compact">
<Card.Title>{selection.getState().size} chosen</Card.Title>
<ul>
{#each rows as row (row.id)}
<li>
<label>
<input
type="checkbox"
checked={selection.isSelected(row.id)}
onclick={(event) => selection.toggle(row.id, { range: event.shiftKey })}
/>
{row.name}
</label>
</li>
{/each}
</ul>
</Card.Root>
When written out is too much
Written out has a price: the fifth table of an app repeats what the first four wrote. The
answer is not a shorter library. The library stays written out, and the app writes its own short
form once, in its own code: a function that fixes the features and the defaults this app uses.
TanStack Table has a function for exactly that, createTableHook: it fixes the features and the
defaults once, and every call still gives its own data, columns and state. A table that stands
alone stays on the long form. The short form belongs to the app; the next app writes another.
The traps of this half
Logic welded to markup
- You see:
<DataTable sortable filterable paginated columns={…} />. The first table that needs another header, a row that opens, or its own empty state can't be built with it. - Fix: two layers. A core that works out state and rows, and parts that render them. The caller joins them.
State nobody can reach
- You see: a filter the page can't put in the address, a dialog that can't be opened from outside, a selection that can't be cleared after a save. Or two copies of one value that drift apart.
- Why: the state sits inside the unit, with no way to read it, set it or hear it change. Or it was copied out into a second place.
- Fix: name every piece. For each: readable always, and one owner. Say which in the options
(
stateandonStateChange, orinitialState).
Arguments by position
- You see:
createList(items, true, false, 20). Nobody can read the call, and the fifth argument breaks every caller. - Fix: one object with named keys, also for the options of a single act. A new key breaks nobody.
Things that happen unasked
- You see: a feature that is on unless it is switched off. A plugin that registers itself when its file is imported. A setting read from a global.
- Fix: the caller writes what it uses, and what is not written does not happen. The all-in set may exist beside it, under a name that says what it costs.
Types the caller has to write
- You see:
useThing<Row, Filters, string>(…), oranyat the edge, or the same list of names typed in three places. - Fix: one definition that is written once, and types that follow from it. A wrong column id or a wrong variant then fails to compile at the call site.
The framework inside the core
- You see: a hook that holds all the logic, so nothing of it can be tested without rendering and nothing can be used from the other framework.
- Fix: the logic in plain functions and values. The hook, the rune or the store is an adapter of a few lines around it.
Sources
- TanStack, "Product Tenets" (tanstack.com/tenets): four tenets, among them Predictable, Explicit, Type-Safe Behavior and Composable, Platform-Aligned Primitives.
@tanstack/table-core9.3.1 and@tanstack/react-table9.3.1, the skills inside the npm packages:core,table-features,table-state, and the referencecreate-table-hook.- TanStack Table docs, version 9: "Overview" (What is "Headless" UI?), "Features Guide" (why the list of features is required: the bundle's size, and types that fit), "Table State", and "Installation" (the core and its adapters).
- TanStack Query docs, version 5: "Migrating to TanStack Query v5" (a single signature, one object), "Query Options", "Query Keys".
- TanStack Router docs, "Overview": types inferred from the routes as they are written, and the search part of the address treated as state.
- Juntao Qiu, "Headless Component: a pattern for composing React UIs" (martinfowler.com, 2023). Kent C. Dodds, "Inversion of Control" (2019).
- Ariya Hidayat, "The Pitfalls of Boolean Trap" (2011): a bare
truecan't be read where it is written.