by DannyUpdated 10 sections

Written for React 19 with function components.

Download the PDF

Components and props


_10
type Props = { name: string; children?: ReactNode };
_10
_10
function Greeting({ name, children }: Props) {
_10
return <h1>Hello {name}{children}</h1>;
_10
}
_10
_10
<Greeting name="Ann">!</Greeting>

JSX rules


_10
<div className="box" style={{ color: 'red' }} />
_10
<label htmlFor="email">Email</label>
_10
<>{a}{b}</> {/* fragment */}
_10
{isOpen && <Modal />} {/* show if true */}
_10
{isOpen ? <Close /> : <Open />}

Lists


_10
<ul>
_10
{items.map((item) => (
_10
<li key={item.id}>{item.label}</li>
_10
))}
_10
</ul>

Keys must be stable and unique among siblings. Avoid the array index if the list can reorder.

useState


_10
const [count, setCount] = useState(0);
_10
setCount(count + 1);
_10
setCount((c) => c + 1); // from latest value
_10
setUser((u) => ({ ...u, name })); // new object

useEffect


_10
useEffect(() => {
_10
const id = setInterval(tick, 1000);
_10
return () => clearInterval(id); // clean up
_10
}, []); // [] = run once after mount

Only use an effect to sync with something outside React. Work out derived values during render instead.

Refs


_10
const inputRef = useRef<HTMLInputElement>(null);
_10
inputRef.current?.focus();
_10
<input ref={inputRef} />
_10
_10
const timer = useRef<number | null>(null);
_10
// a ref survives renders and never causes one

Memo and callbacks


_10
const sorted = useMemo(
_10
() => items.toSorted(byName), [items]);
_10
const onSave = useCallback(
_10
() => save(id), [id]);
_10
const FastRow = memo(Row); // skips equal props

Context


_10
const ThemeContext = createContext('light');
_10
_10
<ThemeContext value="dark">
_10
<App />
_10
</ThemeContext>
_10
_10
const theme = use(ThemeContext);

Forms


_10
<form action={async (data: FormData) => {
_10
await save(data.get('email'));
_10
}}>
_10
<input name="email" type="email" />
_10
<SubmitButton />
_10
</form>
_10
_10
const { pending } = useFormStatus();

Custom hooks


_10
function useToggle(initial = false) {
_10
const [on, setOn] = useState(initial);
_10
const toggle = () => setOn((v) => !v);
_10
return [on, toggle] as const;
_10
}