Sub topic 3
Describing Props with TypeScript
Assume you know JavaScript functions, objects, destructuring, JSX, and basic React components. TypeScript lets you describe a component’s props so the compiler can catch missing or incorrectly typed values.
Type props explicitly
A props type lists the values a component accepts. Use ? for optional props and a default value when one is absent.
type ButtonProps = {
label: string;
variant?: 'primary' | 'secondary';
disabled?: boolean;
onClick: () => void;
};
function Button({
label,
variant = 'primary',
disabled = false,
onClick,
}: ButtonProps) {
return (
<button className={variant} disabled={disabled} onClick={onClick}>
{label}
</button>
);
}The compiler rejects <Button label={42} /> because label must be a string. Union types, such as 'primary' | 'secondary', restrict a value to known choices.
Forward props with spread syntax
A rest pattern separates props your component uses from the remaining props. A spread passes those remaining props to another element.
type TextInputProps = {
label: string;
} & React.ComponentProps<'input'>;
function TextInput({ label, ...inputProps }: TextInputProps) {
return (
<label>
{label}
<input {...inputProps} />
</label>
);
}TextInput can now accept standard input attributes such as type, placeholder, and aria-label. Be deliberate about spread order: later attributes override earlier ones.
> callout note > Do not spread untrusted or unintended props onto elements. It can create invalid attributes or accidentally expose behavior.
`key` and `ref` are special
React uses key to track list items. It is not included in the child component’s ordinary props. Likewise, ref has special handling for accessing a DOM node or component instance. Pass a separate prop when the component needs the same value:
<Item key={item.id} itemId={item.id} />Composition and shared data
Slot props let a parent choose content for named areas. Render props are functions passed as props that return JSX.
function Layout({ header, children }: {
header: React.ReactNode;
children: React.ReactNode;
}) {
return <section><header>{header}</header><main>{children}</main></section>;
}Composition often avoids passing data through components that do not use it. Prop drilling means forwarding the same prop through several layers. Use context when many distant components need the same value, such as a theme or current account. Context reduces plumbing but makes dependencies less visible.
Re-rendering and memo
A parent re-render can cause its children to render again. memo can skip a child render when its props are shallowly equal. New object and function literals have new references, so they can defeat memoization. Use memo only after measuring a real performance problem.
Exercise
Why might memo fail to skip a render when a parent passes onClick={() => save(id)}?
Show answer
The arrow function is newly created on each parent render, so its function reference changes.