Generic Components
Last updated: 2026-11-02
Generic Components Generic Components
Generic components let the type follow the data: a function List<T> renders an array of strings with T=string and an array of objects with T=User. You write it once and every element type gets full inference and hints, which is the core technique behind reusable UI libraries and data-layer wrappers. The component logic stops caring about the shape of the items, so the same code serves any payload the caller hands over.
| Group | Data & Engineering |
|---|---|
| Kind | Pattern |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
type ListProps<T> = {
items: T[]
renderItem: (item: T) => React.ReactNode // the caller decides how to render
keyOf?: (item: T) => string | number
}
function List<T>({ items, renderItem, keyOf }: ListProps<T>) {
return (
<ul>
{items.map((it, i) => (
<li key={keyOf ? keyOf(it) : i}>{renderItem(it)}</li>
))}
</ul>
)
}
// T is inferred automatically at the call site:
<List items={['a', 'b']} renderItem={s => s.toUpperCase()} /> // T = string
<List items={users} renderItem={u => u.name} keyOf={u => u.id} /> // T = User
Returns:No return value; this is a coding pattern rather than a callable API.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
Three lists reuse the same GenericList component to render strings, numbers and objects - generics decouple the component logic from the element type (runtime JSX demo, the types are inferred in the TypeScript version).