React Compound Components

React compound components pattern (safe, minimal context, ergonomic API)

oalkabouss Updated

File contents

What I do

Je fournis un guide pour implémenter des Compound Components sûrs :

  • contexte minimal
  • API ergonomique
  • erreurs explicites

Minimal template

type Ctx = { id: string };
const Ctx = createContext<Ctx | null>(null);

export function Root({ id, children }: { id: string; children: ReactNode }) {
  return <Ctx.Provider value={{ id }}>{children}</Ctx.Provider>;
}

Root.Label = function Label({ children }: { children: ReactNode }) {
  const ctx = useContext(Ctx);
  if (!ctx) throw new Error('Root.Label must be used within Root');
  return <label htmlFor={ctx.id}>{children}</label>;
};

When NOT to use

  • Si l'état partagé devient complexe : passer à props explicites + hook.

oalkabouss/fullstack-agent-skills/tree/main/.claude/skills/react-compound-components commit 16c5288bd4

Frequently asked questions

npx skillmds@latest add oalkabouss/react-compound-components