Sub topic 2
React.FC or a Plain Function?
Assume you know function components, JSX, hooks, and basic TypeScript unions and generics. The examples use strict TypeScript.
Choosing a component style
React.FC<Props> is a type for a React function component. A plain function with a typed parameter is usually simpler and makes the component's inputs clear.
import type { ReactNode } from "react";
interface PanelProps {
title: string;
children?: ReactNode;
}
export function Panel({ title, children }: PanelProps) {
return (
<section>
<h2>{title}</h2>
{children}
</section>
);
}React.FC can still be useful when a codebase consistently uses it or when you want an explicit component return type. It does not automatically add children in current React type definitions, so declare children when the component accepts it.
import type { FC } from "react";
const Heading: FC<{ text: string }> = ({ text }) => <h1>{text}</h1>;A plain function works well with generics and usually produces less type syntax.
Typing event handlers
Use React event types parameterized by the element that emits the event. ChangeEvent<HTMLInputElement> describes an input change, while FormEvent<HTMLFormElement> describes form submission.
import { useState, type ChangeEvent, type FormEvent } from "react";
export function NameForm({
onSubmit,
}: {
onSubmit: (name: string) => void;
}) {
const [name, setName] = useState("");
function handleChange(event: ChangeEvent<HTMLInputElement>) {
setName(event.target.value);
}
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
onSubmit(name);
}
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={handleChange} />
<button type="submit">Save</button>
</form>
);
}Typing state and refs
TypeScript infers string from useState(""). Add a type when the initial value does not show the complete state shape.
A DOM ref starts as null, so include null and use a null-safe access such as ?..
import { useRef, useState } from "react";
interface User {
id: number;
name: string;
}
export function Profile() {
const [user, setUser] = useState<User | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
return (
<div>
<input ref={inputRef} />
<button onClick={() => inputRef.current?.focus()}>Focus</button>
<button onClick={() => setUser({ id: 1, name: "Ada" })}>Load</button>
<p>{user?.name ?? "No user"}</p>
</div>
);
}A ref can also hold a mutable value that does not trigger rendering. For example, useRef<number>(0) can store an interval identifier or counter.
Extending native element props
Use ComponentPropsWithoutRef<"button"> to accept the normal attributes of a button while adding your own props.
import type { ComponentPropsWithoutRef } from "react";
type ButtonProps = ComponentPropsWithoutRef<"button"> & {
variant?: "primary" | "secondary";
};
export function Button({
variant = "primary",
className,
...rest
}: ButtonProps) {
return (
<button className={`button-${variant} ${className ?? ""}`} {...rest} />
);
}This preserves attributes such as disabled, aria-label, and onClick without redefining them.
Exercise
Which type should a ref use for an input DOM node, and why must its initial type include null?
Show answer
UseRef<HTMLInputElement>(null). The ref is null before React attaches the input, so the type must represent both an HTMLInputElement and null.