Catalogue / react-component-assembly
react-component-assembly
Older skill: source not recordedSignedRefactors React interfaces into explicit variants, reusable parts, and interchangeable state providers with typed context contracts. Use when asked to "remove boolean modes", "build compound components", "share state with a sibling", "swap a state provider", or "use React 19 refs"; Not for replacing…--- name: react-component-assembly description: >- Refactors React interfaces into explicit variants, reusable parts, and interchangeable state providers with typed context contracts. Use when asked to "remove boolean modes", "build compound components", "share state with a sibling", "swap a state provider", or "use React 19 refs"; Not for replacing every ordinary boolean prop or changing a project's React version without a compatibility plan. ---
React Component Assembly
The eight rules at a glance
Work through them roughly in this order; earlier rules shape what the later ones can do.
| # | Area | Rule | Impact | |---|---|---|---| | 1 | Component architecture | Replace mode flags with composition | HIGH | | 2 | Component architecture | Build compound components over one shared context | HIGH | | 3 | State management | Keep state handling inside the provider alone | MEDIUM | | 4 | State management | Publish a state/actions/meta contract | MEDIUM | | 5 | State management | Lift shared state into the provider | MEDIUM | | 6 | Implementation | Prefer explicit variant components | MEDIUM | | 7 | Implementation | Compose children before render props | MEDIUM | | 8 | React 19 APIs | Plain ref props and use() for context | MEDIUM |
Rule 8 assumes the project is on React 19 or newer; skip it on React 18.
Find the component's real variants
Inventory rendered parts, state ownership, actions, and consumers outside the main visual box. Separate stable structure from data flowing back to a child. Then name the supported workflows rather than encoding them in combinations of mode flags.
| Review order | Question | Expected result | |---|---|---| | Architecture | Which combinations represent real workflows? | Explicit new/revision/handoff/group variants | | Shared state | Which siblings read or update the same data? | One provider covering all actual consumers | | State interface | What can UI depend on without knowing storage? | State, actions, and metadata contract | | Implementation | Is this static layout or data-dependent rendering? | Children for structure, callback for supplied data | | React compatibility | Is the application on React 19 or earlier? | Appropriate refs/context APIs, not a blind migration |
- Analysis, sketches, and local drafts need no confirmation.
- Editing an exported component's API inside the scope the user explicitly asked to refactor is covered by that request.
- Version upgrades, package installs, and anything that saves or sends data need their own approval.
Keep real booleans; remove hidden workflows
disabled, checked, and a local feature toggle can be valid booleans. The problem is a collection of flags that jointly selects an application's workflow, data source, controls, and actions.
Four independent mode flags permit sixteen combinations, but the product may support only a few. Composition does not automatically prevent impossible states; the exported variants and types must actually express the supported combinations.
A compact before example:
import type { ReactNode } from 'react';
type ModeBoxProps = {
revising: boolean; handingOff: boolean; includeEvidence: boolean;
body: ReactNode; commit: () => void; cancel: () => void;
};
function ModeBox(props: ModeBoxProps) {
return <section>
{props.body}
{props.includeEvidence && <p>Evidence controls</p>}
{props.revising ? <button onClick={props.cancel}>Cancel revision</button> : null}
<button onClick={props.commit}>
{props.revising ? 'Save revision' : props.handingOff ? 'Record handoff' : 'Record observation'}
</button>
</section>;
}The revised surface has named variants with deliberate parts:
| Variant | Provider/input | Visible parts | Action | |---|---|---|---| | NewInspection | Local blank state | Heading/body/evidence/format/symbol | Record locally | | RevisionInspection | Local existing body | Heading/body/format/cancel | Save revision locally | | HandoffInspection | Local initial body | Body/format/symbol/mention plus sibling preview/actions | Record handoff locally | | GroupInspection | Local draft plus group field | Group inclusion control and shared draft parts | Record local review plan | | SharedInspection | Injected external store | Same body/submit parts plus preview | Store-controlled commit |
Each variant states its provider, rendered pieces, and available actions. A new workflow can reuse internals without adding another mode flag to every consumer.
Complete React 19 implementation
Save this whole block as NoteDesk.tsx only in the requested edit scope. It contains every component, type, local provider, external store, and variant used below. React 19 and matching type declarations are required.
The fixture evidence button adds text metadata only. Formatting, symbols, mentions, cancellation, and previews modify draft memory. The injected commit controls persistence; a remote adapter requires that exact destination/action authorized before use.
import {
createContext, use, useCallback, useEffect, useId, useMemo, useRef,
useState, useSyncExternalStore, type ReactNode, type Ref, type RefObject,
} from 'react';
export type Evidence = { id: string; label: string };
export type NoteState = { body: string; evidence: Evidence[]; busy: boolean; problem: string | null };
export type UpdateNote = (change: (previous: NoteState) => NoteState) => void;
export type NoteActions = { update: UpdateNote; submit: () => Promise<void>; reset: () => void };
export type NoteMeta = { inputRef: RefObject<HTMLTextAreaElement | null>; labelId: string; submitLabel: string };
export type NoteValue = { state: NoteState; actions: NoteActions; meta: NoteMeta };
export type CommitNote = (value: Readonly<{ body: string; evidence: readonly Evidence[] }>, signal: AbortSignal) => Promise<void>;
export const blankNote = (): NoteState => ({ body: '', evidence: [], busy: false, problem: null });
export const NoteContext = createContext<NoteValue | null>(null);
export function useNote(): NoteValue {
const value = use(NoteContext);
if (!value) throw new Error('NoteDesk parts require a NoteDesk.Provider ancestor');
return value;
}
export function NoteProvider({ value, children }: { value: NoteValue; children: ReactNode }) {
return <NoteContext value={value}>{children}</NoteContext>;
}
export function LocalNoteProvider({ initialBody = '', commit, children, submitLabel = 'Record locally' }: {
initialBody?: string; commit: CommitNote; children: ReactNode; submitLabel?: string;
}) {
const [state, setState] = useState<NoteState>(() => ({ ...blankNote(), body: initialBody }));
const inputRef = useRef<HTMLTextAreaElement | null>(null);
const controller = useRef<AbortController | null>(null);
const labelId = useId();
useEffect(() => () => { controller.current?.abort(); }, []);
const submit = useCallback(async () => {
if (controller.current || !state.body.trim()) return;
const active = new AbortController();
controller.current = active;
setState(previous => ({ ...previous, busy: true, problem: null }));
try {
await commit({ body: state.body, evidence: state.evidence }, active.signal);
if (!active.signal.aborted) setState(previous => previous.body === state.body && previous.evidence === state.evidence
? { ...previous, body: '', evidence: [] } : previous);
} catch (error) {
if (!active.signal.aborted) setState(previous => ({ ...previous,
problem: error instanceof Error ? error.message : 'Unable to record note' }));
} finally {
if (controller.current === active) controller.current = null;
if (!active.signal.aborted) setState(previous => ({ ...previous, busy: false }));
}
}, [commit, state.body, state.evidence]);
const reset = useCallback(() => { if (!controller.current) setState(blankNote()); }, []);
const value = useMemo<NoteValue>(() => ({ state, actions: { update: setState, submit, reset },
meta: { inputRef, labelId, submitLabel } }), [state, submit, reset, labelId, submitLabel]);
return <NoteProvider value={value}>{children}</NoteProvider>;
}
export type NoteStore = {
getSnapshot: () => NoteState;
subscribe: (listener: () => void) => () => void;
update: UpdateNote;
submit: () => Promise<void>;
reset: () => void;
};
export function createNoteStore(commit: CommitNote, initialBody = ''): NoteStore {
let state: NoteState = { ...blankNote(), body: initialBody };
let active: AbortController | null = null;
const listeners = new Set<() => void>();
const update: UpdateNote = change => { state = change(state); for (const listener of listeners) listener(); };
return {
getSnapshot: () => state,
subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
update,
reset() { if (!active) update(() => blankNote()); },
async submit() {
if (active || !state.body.trim()) return;
const request = new AbortController(); active = request;
const payload = { body: state.body, evidence: state.evidence };
update(previous => ({ ...previous, busy: true, problem: null }));
try {
await commit(payload, request.signal);
update(previous => previous.body === payload.body && previous.evidence === payload.evidence
? { ...previous, body: '', evidence: [] } : previous);
} catch (error) {
update(previous => ({ ...previous, problem: error instanceof Error ? error.message : 'Unable to record note' }));
} finally {
active = null;
update(previous => ({ ...previous, busy: false }));
}
},
};
}
export function SharedNoteProvider({ store, children, submitLabel = 'Record shared note' }: {
store: NoteStore; children: ReactNode; submitLabel?: string;
}) {
const state = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
const inputRef = useRef<HTMLTextAreaElement | null>(null);
const labelId = useId();
const value = useMemo<NoteValue>(() => ({ state, actions: { update: store.update, submit: store.submit, reset: store.reset },
meta: { inputRef, labelId, submitLabel } }), [state, store, labelId, submitLabel]);
return <NoteProvider value={value}>{children}</NoteProvider>;
}
function Frame({ children }: { children: ReactNode }) {
const { actions } = useNote();
return <form onSubmit={event => { event.preventDefault(); void actions.submit(); }}>{children}</form>;
}
function Heading({ children }: { children: ReactNode }) {
const { meta } = useNote();
return <label id={meta.labelId}>{children}</label>;
}
function Body({ placeholder = 'Write an observation' }: { placeholder?: string }) {
const { state, actions, meta } = useNote();
return <textarea ref={meta.inputRef} aria-labelledby={meta.labelId} value={state.body}
placeholder={placeholder} disabled={state.busy}
onChange={event => actions.update(previous => ({ ...previous, body: event.target.value }))} />;
}
function Footer({ children }: { children: ReactNode }) { return <footer>{children}</footer>; }
function Submit() {
const { state, actions, meta } = useNote();
return <button type="button" disabled={state.busy || !state.body.trim()} onClick={() => { void actions.submit(); }}>
{state.busy ? 'Recording…' : meta.submitLabel}
</button>;
}
function Cancel() {
const { state, actions } = useNote();
return <button type="button" disabled={state.busy} onClick={actions.reset}>Discard local draft</button>;
}
function EvidenceList() {
const { state, actions } = useNote();
return <section aria-label="Evidence">
<button type="button" disabled={state.busy} onClick={() => actions.update(previous => ({ ...previous,
evidence: [...previous.evidence, { id: `fixture-${previous.evidence.length + 1}`, label: 'Synthetic evidence item' }] }))}>
Add fixture evidence
</button>
<ul>{state.evidence.map(item => <li key={item.id}>{item.label}</li>)}</ul>
</section>;
}Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 25.0 kB | dff8e7bd33de |
| examples.json | 2.4 kB | 65a17297d268 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.0 Current | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.