React
Components, hooks, state, effects, performance, composition patterns, React 19 basics, and a React 16–19.3 evolution reference. · 32 lessons · click a card to expand
Fundamentals first (32 lessons). Expand a lesson to run marked JSX examples inline. React hub has interview prep and Evolution chapters.
This page is the fundamentals track (32 lessons). After you can build components, hooks, and forms, continue in [React Evolution](/notes/learn/react/evolution) — a React 16 → 19.3 reference covering Fiber, concurrent rendering, Actions, migrations, and recent 19.x APIs.
- Start here if you are learning React.
- Open React Evolution if you already know hooks and want version-by-version depth.
- Interview-style Q&A lives at React notes.
Mental model & JSX
4 items01React is a UI library, not a framework
// UI = f(state)
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
// React renders this into the DOM:
// <div id="root"></div> → <h1>Hello, Ada!</h1>
import { createRoot } from "react-dom/client";
createRoot(document.getElementById("root")).render(
<Greeting name="Ada" />
);React does not ship a router, global store, or HTTP client. That separation keeps the core small and lets you pick tools (React Router, TanStack Query, Zustand, etc.). Think of React as the view layer in a larger architecture.
npm create vite@latest my-app -- --template react). Replace App.jsx with Greeting above and render it with your name.02JSX is syntax sugar for React.createElement
createElement (or _jsx in modern runtimes) call that returns a plain object — a React element, not a DOM node.{}, and a fragment all have precise JavaScript equivalents.// What you write:
const element = (
<>
<h1 className="title">Welcome</h1>
<p>{user.name} has {user.score} points</p>
</>
);
// What the compiler produces (simplified):
const element = React.createElement(
React.Fragment,
null,
React.createElement("h1", { className: "title" }, "Welcome"),
React.createElement(
"p",
null,
user.name,
" has ",
user.score,
" points"
)
);A React element is a lightweight description: { type, props, key }. React reads these descriptions and creates or updates real DOM nodes during commit.
className instead of class, htmlFor instead of for, and camelCase for DOM attributes (tabIndex, onClick). JSX is JavaScript, not HTML.console.log(<span>test</span>). Inspect the object shape in the console.03Embedding expressions, conditionals, and fragments
{} embed any JavaScript expression in JSX. Conditionals use ternaries, &&, or early returns — not if statements inside JSX tags.function StatusBadge({ status, count }) {
// Early return for loading / error states
if (status === "loading") return <span className="badge">Loading…</span>;
if (status === "error") return <span className="badge error">Failed</span>;
return (
<>
{/* Ternary for two clear branches */}
<span className={count > 0 ? "badge active" : "badge"}>
{count > 0 ? `${count} items` : "Empty"}
</span>
{/* && for "render when truthy" — beware: 0 renders "0" */}
{count > 0 && <button>Clear all</button>}
</>
);
}Fragments (<>...</> or <React.Fragment>) group siblings without adding an extra DOM node. Use the keyed form <Fragment key={id}> when mapping lists of fragments.
const content = status === "ok" ? <Ok /> : <Fail />;UserCard that shows an avatar image when avatarUrl exists, a placeholder div when it does not, and a "Premium" badge only when isPremium is true.04The component tree and one-way data flow
App) holds top-level state and passes slices down. A child never mutates props directly — it calls onSave(data) and lets the parent update state and re-render the tree.function App() {
const [query, setQuery] = useState("");
return (
<div>
<SearchBar value={query} onChange={setQuery} />
<ResultsList query={query} />
</div>
);
}
function SearchBar({ value, onChange }) {
return (
<input
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder="Search…"
/>
);
}
function ResultsList({ query }) {
const items = useMemo(() => filterItems(query), [query]);
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.label}</li>
))}
</ul>
);
}This unidirectional flow makes bugs easier to trace: find the component that owns the state, then follow props downward and callbacks upward.
App holds count and CounterDisplay shows it while CounterButtons receives onIncrement and onDecrement callbacks.Components & props
3 items05Function components and returning UI
null). They replace class components for virtually all new code.function Avatar({ src, alt, size = 48 }) {
const style = {
width: size,
height: size,
borderRadius: "50%",
objectFit: "cover",
};
if (!src) return null; // render nothing
return <img src={src} alt={alt} style={style} />;
}
function ProfileHeader({ user }) {
return (
<header>
<Avatar src={user.avatarUrl} alt={user.name} size={64} />
<h2>{user.name}</h2>
<p>{user.bio}</p>
</header>
);
}Components can be defined in the same file or exported from modules. Keep components focused: if a function returns JSX and has a clear name, it is probably a component.
Avatar(props)). Always use JSX (<Avatar {...props} />) so React can track hooks, keys, and reconciliation correctly.Avatar, ProfileHeader, and ProfileStats components in separate files and compose them in App.06Props: reading, defaults, and the children prop
children for composition slots.function Card({ title, footer, children, variant = "default" }) {
return (
<article className={`card card--${variant}`}>
{title && <h3>{title}</h3>}
<div className="card__body">{children}</div>
{footer && <footer className="card__footer">{footer}</footer>}
</article>
);
}
function App() {
return (
<Card
title="Weekly summary"
footer={<button>Export PDF</button>}
variant="highlight"
>
<p>You completed 12 tasks this week.</p>
</Card>
);
}The special prop `children` is whatever you nest between opening and closing tags. It enables flexible layout without prop drilling every possible slot name.
Panel component with optional title, required children, and an optional actions prop that renders a button row in the header.07PropTypes, key rules, and component boundaries
key inside a child — keys belong on the outermost element returned from a .map() in the parent.import PropTypes from "prop-types";
function TagList({ tags }) {
return (
<ul>
{tags.map((tag) => (
// key on the element returned from map — here in the parent
<li key={tag.id}>
<Tag label={tag.label} color={tag.color} />
</li>
))}
</ul>
);
}
function Tag({ label, color }) {
// Do NOT: key={label} here — Tag does not know its list context
return <span style={{ background: color }}>{label}</span>;
}
Tag.propTypes = {
label: PropTypes.string.isRequired,
color: PropTypes.string,
};Keys must be stable, unique among siblings. Index-as-key is acceptable only for static lists that never reorder, filter, or insert in the middle.
TodoList that maps todos to TodoItem components. Reorder todos with up/down buttons and confirm items keep correct state when keys use id vs array index.State & re-renders
3 items08Local state with useState
useState adds reactive state to a function component. Calling the setter schedules a re-render; React preserves state between renders by hook call order.[value, setValue] = useState(initialValue). The initial value is used only on the first render. Functional updates receive the previous state and avoid stale closures.import { useState } from "react";
export default function SignupForm() {
const [email, setEmail] = useState("");
const [step, setStep] = useState(1);
function nextStep() {
setStep((prev) => prev + 1); // functional update — safe in async paths
}
return (
<form onSubmit={(e) => e.preventDefault()}>
{step === 1 && (
<input
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
/>
)}
{step === 2 && <p>Confirm: {email}</p>}
<button type="button" onClick={nextStep}>Next</button>
</form>
);
}Click Run to render this example.
Each useState call is a separate slice of state. Group related fields in one object only when they always update together — otherwise prefer multiple hooks for simpler updates.
state.items.push(x)). Always create new references so React detects change: setItems((prev) => [...prev, x]).useState tracking the active tab index. Switching tabs should preserve each panel's internal input values (lift inputs into tab state if needed).09What triggers a re-render and render purity
useEffect, not in the render body.function ExpensiveList({ items, filter }) {
// BAD — side effect during render
// document.title = `Showing ${items.length} items`;
// GOOD — derive during render (pure)
const visible = items.filter((item) =>
item.label.toLowerCase().includes(filter.toLowerCase())
);
console.log("ExpensiveList render"); // runs every time parent or local state changes
return (
<ul>
{visible.map((item) => (
<li key={item.id}>{item.label}</li>
))}
</ul>
);
}Calling setState during render (except in rare controlled patterns) causes infinite loops. Batch multiple setState calls in event handlers — React 18+ batches them automatically, even across async boundaries in many cases.
useMemo (Lesson 16) — but do not optimize prematurely.console.log to several nested components. Click a button that updates state in the root and observe which components re-render. Wrap one child in React.memo (Lesson 27) and compare.10Lifting state up and controlled vs uncontrolled inputs
function TemperatureConverter() {
const [celsius, setCelsius] = useState("");
const fahrenheit =
celsius === "" ? "" : String((Number(celsius) * 9) / 5 + 32);
return (
<div>
<LabeledInput
label="Celsius"
value={celsius}
onChange={setCelsius}
/>
<LabeledInput
label="Fahrenheit"
value={fahrenheit}
onChange={(f) => setCelsius(String(((Number(f) - 32) * 5) / 9))}
/>
</div>
);
}
function LabeledInput({ label, value, onChange }) {
return (
<label>
{label}
<input value={value} onChange={(e) => onChange(e.target.value)} />
</label>
);
}Use controlled inputs for live validation and instant UI feedback. Use uncontrolled + ref for simple forms where you read values only on submit.
0 — mixing "" and 0 causes subtle bugs in calculations.Cart holds items array state and ProductList / CartSummary siblings both read from and update through callbacks passed from App.Hooks: useState, useEffect, useRef
5 items11Rules of Hooks and hook call order
// WRONG — conditional hook
function Bad({ show }) {
if (show) {
const [x, setX] = useState(0); // violates rules
}
return null;
}
// RIGHT — hook always called; condition inside
function Good({ show }) {
const [x, setX] = useState(0);
if (!show) return null;
return <button onClick={() => setX(x + 1)}>{x}</button>;
}
// Custom hooks extract reusable logic — they follow the same rules
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = () => setOn((v) => !v);
return [on, toggle];
}ESLint plugin eslint-plugin-react-hooks enforces these rules. Enable it in every React project.
useSomething so linters and teammates recognize them as hooks.useToggle and confirm both still work after a conditional early return *below* the hook call.12useEffect for synchronizing with external systems
useEffect runs after paint to sync React state with the outside world: DOM APIs, subscriptions, timers, and network fetches. The optional cleanup function runs before the next effect and on unmount.import { useEffect, useState } from "react";
function DocumentTitle({ title }) {
useEffect(() => {
const previous = document.title;
document.title = title;
return () => {
document.title = previous; // cleanup on title change or unmount
};
}, [title]);
return null;
}
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
useEffect(() => {
const connection = createConnection(roomId);
connection.on("message", (msg) => {
setMessages((prev) => [...prev, msg]);
});
connection.connect();
return () => connection.disconnect(); // leave room on roomId change
}, [roomId]);
return <MessageList messages={messages} />;
}An empty dependency array [] means "run once after mount" (plus cleanup on unmount). Omitting the array means "run after every render" — rarely what you want.
WindowWidth component that listens to resize events and displays the current inner width. Verify the listener is removed in cleanup by logging in the effect and cleanup.13Effect dependencies and stale closures
exhaustive-deps rule helps, but understanding *why* matters. Functional state updates and refs are tools to reduce dependency churn.function Timer({ intervalMs }) {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
// Functional update — does not need `seconds` in deps
setSeconds((s) => s + 1);
}, intervalMs);
return () => clearInterval(id);
}, [intervalMs]); // re-subscribe when interval changes
return <p>{seconds}s</p>;
}
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
let cancelled = false;
async function run() {
const data = await fetchResults(query);
if (!cancelled) setResults(data);
}
run();
return () => {
cancelled = true; // ignore outdated responses when query changes fast
};
}, [query]);
return <ul>{results.map((r) => <li key={r.id}>{r.title}</li>)}</ul>;
}useEffectEvent (React 19) or storing callbacks in refs — but do not disable exhaustive-deps without a documented reason.14useRef for mutable values and DOM access
useRef returns a mutable { current } object that persists across renders without causing re-renders when mutated. Use it for DOM nodes, timer IDs, and instance variables.ref.current does not trigger a render. Assign the ref to a JSX element via the ref attribute.import { useEffect, useRef, useState } from "react";
function FocusableInput() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current?.focus();
}
return (
<>
<input ref={inputRef} placeholder="Click button to focus me" />
<button type="button" onClick={focusInput}>Focus</button>
</>
);
}
function Stopwatch() {
const [elapsed, setElapsed] = useState(0);
const intervalRef = useRef(null);
function start() {
if (intervalRef.current) return;
intervalRef.current = setInterval(() => {
setElapsed((e) => e + 1);
}, 1000);
}
function stop() {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
return (
<div>
<p>{elapsed}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</div>
);
}ref.current during render (except initialization patterns documented by React). DOM refs are populated after commit; use effects or event handlers to interact with them.scrollHeight and set inline height on input events.15Custom hooks: extracting reusable logic
useState + useEffect combo into three components, extract a function named useSomething.function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
function SettingsPanel() {
const [theme, setTheme] = useLocalStorage("theme", "light");
return (
<select value={theme} onChange={(e) => setTheme(e.target.value)}>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
);
}
function useDebouncedValue(value, delayMs) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(id);
}, [value, delayMs]);
return debounced;
}Custom hooks can call other hooks. They are the primary mechanism for sharing behavior in modern React codebases.
useState style) and objects for named fields when there are many return values.useDebouncedValue and wire it to a search input that filters a list only after 300 ms of idle typing.Hooks: useMemo, useCallback, useReducer, useContext
5 items16useMemo for expensive derived values
useMemo caches the result of a computation between renders, recomputing only when dependencies change. Use it for measurable expensive work — not for every inline object.Object.is. The memoized value survives re-renders caused by unrelated state updates.import { useMemo, useState } from "react";
function DataGrid({ rows, sortKey, filterText }) {
const processedRows = useMemo(() => {
console.log("sorting and filtering…");
const filtered = rows.filter((row) =>
row.name.toLowerCase().includes(filterText.toLowerCase())
);
return [...filtered].sort((a, b) =>
String(a[sortKey]).localeCompare(String(b[sortKey]))
);
}, [rows, sortKey, filterText]);
return (
<table>
<tbody>
{processedRows.map((row) => (
<tr key={row.id}>
<td>{row.name}</td>
<td>{row.score}</td>
</tr>
))}
</tbody>
</table>
);
}If no dependency changed, React skips the function and returns the cached value. This pairs well with React.memo on child components that receive the memoized result as props.
useMemo; the hook itself has a cost.console.log inside a heavy useMemo callback. Toggle unrelated UI state and confirm the log does not run until rows, sortKey, or filterText change.17useCallback for stable function references
useCallback returns a memoized function identity, recomputing the function only when dependencies change. It helps prevent unnecessary re-renders of memoized children that compare props by reference.useCallback.import { memo, useCallback, useState } from "react";
const Row = memo(function Row({ item, onSelect }) {
console.log("Row render", item.id);
return (
<tr onClick={() => onSelect(item.id)}>
<td>{item.label}</td>
</tr>
);
});
function Table({ items }) {
const [selectedId, setSelectedId] = useState(null);
const handleSelect = useCallback((id) => {
setSelectedId(id);
}, []); // stable — setSelectedId identity is stable
return (
<table>
<tbody>
{items.map((item) => (
<Row key={item.id} item={item} onSelect={handleSelect} />
))}
</tbody>
</table>
);
}useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). Do not wrap every handler — only those passed to optimized children or listed in other hooks' dependency arrays.
useCallback when profiling shows avoidable child renders.useCallback and memo from the example above, click unrelated state in Table, and watch all rows re-render in the console. Re-add optimizations and compare.18useReducer for complex state transitions
useReducer models state as (state, action) => newState. Prefer it when the next state depends on multiple fields, previous state, or a sequence of discrete event types.const initialState = { status: "idle", data: null, error: null };
function fetchReducer(state, action) {
switch (action.type) {
case "fetch/start":
return { ...state, status: "loading", error: null };
case "fetch/success":
return { status: "success", data: action.payload, error: null };
case "fetch/error":
return { status: "error", data: null, error: action.payload };
case "reset":
return initialState;
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
function UserProfile({ userId }) {
const [state, dispatch] = useReducer(fetchReducer, initialState);
useEffect(() => {
let cancelled = false;
dispatch({ type: "fetch/start" });
fetchUser(userId)
.then((data) => {
if (!cancelled) dispatch({ type: "fetch/success", payload: data });
})
.catch((err) => {
if (!cancelled) dispatch({ type: "fetch/error", payload: err.message });
});
return () => {
cancelled = true;
};
}, [userId]);
if (state.status === "loading") return <p>Loading…</p>;
if (state.status === "error") return <p>Error: {state.error}</p>;
return <pre>{JSON.stringify(state.data, null, 2)}</pre>;
}You can pass a third argument to useReducer for lazy initialization: useReducer(reducer, initialArg, initFn).
useState calls into one useReducer with actions like SET_FIELD, SUBMIT_START, and SUBMIT_ERROR.19useReducer vs useState and combining with context
useState until updates become hard to reason about — then switch to useReducer. Pair useReducer with Context to distribute dispatch without prop drilling.useState is simpler for independent values. useReducer shines when actions are enumerated and transitions are testable in isolation.function cartReducer(state, action) {
switch (action.type) {
case "add": {
const existing = state.items.find((i) => i.id === action.item.id);
if (existing) {
return {
items: state.items.map((i) =>
i.id === action.item.id
? { ...i, qty: i.qty + 1 }
: i
),
};
}
return { items: [...state.items, { ...action.item, qty: 1 }] };
}
case "remove":
return {
items: state.items.filter((i) => i.id !== action.id),
};
default:
return state;
}
}
const CartContext = createContext(null);
function CartProvider({ children }) {
const [state, dispatch] = useReducer(cartReducer, { items: [] });
const value = useMemo(() => ({ state, dispatch }), [state]);
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}Export a custom hook useCart() that reads context and throws if used outside the provider — a pattern you'll refine in Lesson 20.
cartReducer with a table of [previousState, action, expectedState] cases in Vitest or Jest without rendering any components.20useContext for avoiding prop drilling
useContext, skipping intermediate components. It is for global-ish data (theme, locale, auth session) — not a replacement for every prop.createContext(defaultValue), provide with <Context.Provider value={...}>, consume with useContext. Changing the value re-renders all consuming components unless you split contexts or memoize carefully.import { createContext, useContext, useMemo, useState } from "react";
const ThemeContext = createContext("light");
function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
const value = useMemo(
() => ({ theme, setTheme, isDark: theme === "dark" }),
[theme]
);
return (
<ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
);
}
function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error("useTheme must be used within ThemeProvider");
return ctx;
}
function ThemeToggle() {
const { theme, setTheme, isDark } = useTheme();
return (
<button onClick={() => setTheme(isDark ? "light" : "dark")}>
Current: {theme}
</button>
);
}Split state and dispatch into separate contexts if consumers only need dispatch and should not re-render on state changes.
ThemeProvider and style components with isDark from useTheme. Confirm intermediate layout components do not pass theme props manually.Lists & keys, forms
3 items21Rendering lists and choosing keys
.map(). Keys must identify each sibling stably across inserts, deletes, and reorders — prefer database IDs over array indices for dynamic lists.import { useState } from "react";
export default function TodoApp() {
const [todos, setTodos] = useState([
{ id: "a1", text: "Learn JSX", done: false },
{ id: "b2", text: "Learn hooks", done: false },
]);
function toggle(id) {
setTodos((prev) =>
prev.map((todo) =>
todo.id === id ? { ...todo, done: !todo.done } : todo
)
);
}
return (
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} todo={todo} onToggle={() => toggle(todo.id)} />
))}
</ul>
);
}
function TodoItem({ todo, onToggle }) {
return (
<li>
<label>
<input type="checkbox" checked={todo.done} onChange={onToggle} />
{todo.text}
</label>
</li>
);
}Click Run to render this example.
Never key={Math.random()} — keys must be stable for a given item across renders.
crypto.randomUUID()), not at render time.key={id} vs key={index} when toggling checkboxes before reordering.22Forms: controlled inputs, validation, and submission
preventDefault() on submit. Group related fields in one state object or useReducer for larger forms.import { useState } from "react";
export default function LoginForm() {
const [values, setValues] = useState({ email: "", password: "" });
const [errors, setErrors] = useState({});
const [done, setDone] = useState(false);
function validate(v) {
const next = {};
if (!v.email.includes("@")) next.email = "Enter a valid email";
if (v.password.length < 8) next.password = "At least 8 characters";
return next;
}
function handleChange(e) {
const { name, value } = e.target;
setValues((prev) => ({ ...prev, [name]: value }));
}
function handleSubmit(e) {
e.preventDefault();
const nextErrors = validate(values);
setErrors(nextErrors);
if (Object.keys(nextErrors).length === 0) {
setDone(true);
}
}
if (done) return <p role="status">Signed in as {values.email}</p>;
return (
<form onSubmit={handleSubmit} noValidate>
<label>
Email
<input name="email" value={values.email} onChange={handleChange} />
{errors.email && <span role="alert">{errors.email}</span>}
</label>
<label>
Password
<input
name="password"
type="password"
value={values.password}
onChange={handleChange}
/>
{errors.password && <span role="alert">{errors.password}</span>}
</label>
<button type="submit">Sign in</button>
</form>
);
}Click Run to render this example.
For large forms, libraries like React Hook Form reduce re-renders by registering uncontrolled inputs — learn controlled forms first to understand the underlying model.
aria-invalid and aria-describedby for accessible forms.status === "submitting".23Uncontrolled forms, refs, and file inputs
value for security reasons. Refs bridge imperative DOM APIs into React.import { useRef } from "react";
function AvatarUpload({ onUpload }) {
const fileRef = useRef(null);
function handleSubmit(e) {
e.preventDefault();
const file = fileRef.current?.files?.[0];
if (file) onUpload(file);
}
return (
<form onSubmit={handleSubmit}>
<input ref={fileRef} type="file" accept="image/*" />
<button type="submit">Upload</button>
</form>
);
}
function QuickNoteForm({ onSave }) {
const textRef = useRef(null);
function handleSave() {
const text = textRef.current?.value?.trim() ?? "";
if (text) {
onSave(text);
textRef.current.value = "";
}
}
return (
<>
<textarea ref={textRef} placeholder="Jot a note…" rows={3} />
<button type="button" onClick={handleSave}>Save</button>
</>
);
}React 19 adds ref-as-prop on function components, reducing forwardRef boilerplate (Lesson 30).
formRef.current.reset().Composition patterns
3 items24children and compound components
showHeader, showFooter), nest components and use children or small compound subcomponents (Card.Header, Card.Body).const TabsContext = createContext(null);
function Tabs({ value, onChange, children }) {
return (
<TabsContext.Provider value={{ value, onChange }}>
<div className="tabs">{children}</div>
</TabsContext.Provider>
);
}
Tabs.List = function TabsList({ children }) {
return <div role="tablist">{children}</div>;
};
Tabs.Tab = function Tab({ id, children }) {
const { value, onChange } = useContext(TabsContext);
const selected = value === id;
return (
<button
role="tab"
aria-selected={selected}
onClick={() => onChange(id)}
>
{children}
</button>
);
};
Tabs.Panel = function TabPanel({ id, children }) {
const { value } = useContext(TabsContext);
if (value !== id) return null;
return <div role="tabpanel">{children}</div>;
};
// Usage:
// <Tabs value={tab} onChange={setTab}>
// <Tabs.List>
// <Tabs.Tab id="a">General</Tabs.Tab>
// <Tabs.Tab id="b">Security</Tabs.Tab>
// </Tabs.List>
// <Tabs.Panel id="a">…</Tabs.Panel>
// <Tabs.Panel id="b">…</Tabs.Panel>
// </Tabs>Tabs.List) document structure in JSX and avoid invalid combinations at a glance.Modal (title, body, footer, size, closable) into composable Modal, Modal.Header, Modal.Body, and Modal.Footer parts.25Render props and inversion of control
function MouseTracker({ render }) {
const [pos, setPos] = useState({ x: 0, y: 0 });
useEffect(() => {
function handleMove(e) {
setPos({ x: e.clientX, y: e.clientY });
}
window.addEventListener("mousemove", handleMove);
return () => window.removeEventListener("mousemove", handleMove);
}, []);
return render(pos);
}
function App() {
return (
<MouseTracker
render={({ x, y }) => (
<p style={{ position: "fixed", top: y, left: x }}>
Cursor: {x}, {y}
</p>
)}
/>
);
}
// Same idea as children-as-function:
// <MouseTracker>{(pos) => <Crosshair {...pos} />}</MouseTracker>Custom hooks often replace render props today (useMousePosition), but headless UI libraries still expose render-prop or slot APIs for maximum flexibility.
renderX or use children as a function — be consistent within your design system.DataLoader component that accepts url and children(status, data) and handles loading/error/success states internally.26Lifting content with portal and layout composition
createPortal renders children into a different DOM node (often document.body) while preserving React tree context — essential for modals, tooltips, and toasts. Layout composition nests shells without prop explosion.import { createPortal } from "react-dom";
function Modal({ open, onClose, children }) {
if (!open) return null;
return createPortal(
<div className="modal-backdrop" onClick={onClose}>
<div
className="modal"
onClick={(e) => e.stopPropagation()}
role="dialog"
aria-modal="true"
>
<button className="modal__close" onClick={onClose} aria-label="Close">
×
</button>
{children}
</div>
</div>,
document.body
);
}
function AppShell({ sidebar, header, children }) {
return (
<div className="shell">
<aside>{sidebar}</aside>
<div className="shell__main">
<header>{header}</header>
<main>{children}</main>
</div>
</div>
);
}Compose pages by slotting regions: <AppShell sidebar={<Nav />} header={<TopBar />}>…</AppShell>.
@radix-ui/react-dialog or similar battle-tested primitives.body.Performance & memo
2 items27React.memo and when memoization helps
React.memo skips re-rendering a component if props are shallowly equal to the previous render. It helps when a child is expensive and often receives identical props while siblings update frequently.import { memo, useState } from "react";
const HeavyChart = memo(function HeavyChart({ data, width, height }) {
console.log("HeavyChart render");
// imagine D3 or canvas work here
return <svg width={width} height={height}>{/* … */}</svg>;
});
function Dashboard() {
const [filter, setFilter] = useState("");
const [data] = useState(() => generateLargeDataset());
return (
<div>
<input value={filter} onChange={(e) => setFilter(e.target.value)} />
{/* Chart ignores filter — memo avoids re-render on every keystroke */}
<HeavyChart data={data} width={600} height={400} />
<FilteredTable data={data} filter={filter} />
</div>
);
}Custom compare function as second argument: memo(Component, (prev, next) => prev.id === next.id).
style={{}}) defeats memo. Stabilize with useMemo or move constants outside the component.memo, type in a sibling input, and count renders with and without inline object props passed to the chart.28Code splitting, lazy loading, and virtualization
React.lazy and Suspense so users download code when needed. Virtualize long lists so React renders only visible rows.import { lazy, Suspense, useState } from "react";
const AdminPanel = lazy(() => import("./AdminPanel"));
function App() {
const [route, setRoute] = useState("home");
return (
<div>
<nav>
<button onClick={() => setRoute("home")}>Home</button>
<button onClick={() => setRoute("admin")}>Admin</button>
</nav>
<Suspense fallback={<p>Loading module…</p>}>
{route === "admin" ? <AdminPanel /> : <HomePage />}
</Suspense>
</div>
);
}
// Virtual list sketch (conceptual API):
// <FixedSizeList height={400} itemCount={items.length} itemSize={36}>
// {({ index, style }) => <Row style={style} item={items[index]} />}
// </FixedSizeList>Suspense boundaries catch lazy components and data loaders (with supporting frameworks). Place fallbacks at meaningful UI granularity — skeleton cards, not one global spinner for the entire app.
React 19 basics
2 items29Actions, useActionState, and pending UI
useActionState wraps an action with state returned to the component.useTransition semantics: the UI can show pending feedback while an async operation runs, without manual isLoading boilerplate in every form.import { useActionState } from "react";
async function subscribe(prevState, formData) {
const email = formData.get("email");
if (!email || !String(email).includes("@")) {
return { ok: false, message: "Valid email required" };
}
try {
await fetch("/api/subscribe", {
method: "POST",
body: JSON.stringify({ email }),
});
return { ok: true, message: "Subscribed!" };
} catch {
return { ok: false, message: "Network error — try again" };
}
}
function NewsletterForm() {
const [state, formAction, isPending] = useActionState(subscribe, {
ok: null,
message: "",
});
return (
<form action={formAction}>
<input name="email" type="email" placeholder="you@example.com" />
<button disabled={isPending}>
{isPending ? "Subscribing…" : "Subscribe"}
</button>
{state.message && (
<p role="status">{state.message}</p>
)}
</form>
);
}The notes preview cannot call fetch. This client-only version uses a delay so you can run the same Action pattern here.
import { useActionState } from "react";
async function subscribe(_prev, formData) {
const email = String(formData.get("email") || "");
await new Promise((resolve) => setTimeout(resolve, 400));
if (!email.includes("@")) {
return { ok: false, message: "Valid email required" };
}
return { ok: true, message: `Subscribed ${email}` };
}
export default function NewsletterForm() {
const [state, formAction, isPending] = useActionState(subscribe, {
ok: false,
message: "",
});
return (
<form action={formAction}>
<input name="email" type="email" placeholder="you@example.com" />
<button disabled={isPending}>
{isPending ? "Subscribing…" : "Subscribe"}
</button>
{state.message ? <p role="status">{state.message}</p> : null}
</form>
);
}Click Run to render this example.
Server Components in frameworks like Next.js extend this model — actions can run on the server. In client-only Vite apps, actions still improve form state ergonomics.
formRef.current.reset() or keyed remounts (key={state.ok}).useState loading flag form to useActionState. Handle validation errors returned from the action without separate errors state.30use, ref as prop, and Document Metadata
use(promise) for reading promises in render (with Suspense), allows ref as a regular prop on function components, and supports <title>, <meta>, and <link> anywhere in the tree for document head management.import { Suspense, use, useState } from "react";
// ref as prop — no forwardRef required
function TextInput({ ref, label, ...props }) {
return (
<label>
{label}
<input ref={ref} {...props} />
</label>
);
}
function UserDetails({ userPromise }) {
const user = use(userPromise); // suspends until promise resolves
return (
<>
<title>{user.name} — Profile</title>
<meta name="description" content={user.bio} />
<h1>{user.name}</h1>
<p>{user.bio}</p>
</>
);
}
function ProfilePage({ fetchUser }) {
const [userPromise] = useState(() => fetchUser());
return (
<Suspense fallback={<p>Loading profile…</p>}>
<UserDetails userPromise={userPromise} />
</Suspense>
);
}use can also read context conditionally — unlike useContext, which must be unconditional — but still follow hook rules for production code paths.
use patterns are stable in your stack. Adopt ref-as-prop when upgrading component libraries to React 19.forwardRef input wrapper to accept ref as a prop. Add a <title> inside a nested component and confirm it updates document.title when data loads.TypeScript patterns
2 items31Typing components, props, and events
children explicitly, and use React's event types for handlers.import {
type ChangeEvent,
type FormEvent,
type ReactNode,
useState,
} from "react";
interface SearchFieldProps {
label: string;
value: string;
onChange: (value: string) => void;
placeholder?: string;
children?: ReactNode;
}
function SearchField({
label,
value,
onChange,
placeholder,
children,
}: SearchFieldProps) {
function handleChange(e: ChangeEvent<HTMLInputElement>) {
onChange(e.target.value);
}
return (
<label>
{label}
<input value={value} onChange={handleChange} placeholder={placeholder} />
{children}
</label>
);
}
interface FormValues {
query: string;
}
function SearchForm({ onSearch }: { onSearch: (query: string) => void }) {
const [values, setValues] = useState<FormValues>({ query: "" });
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
onSearch(values.query);
}
return (
<form onSubmit={handleSubmit}>
<SearchField
label="Search"
value={values.query}
onChange={(query) => setValues({ query })}
/>
<button type="submit">Go</button>
</form>
);
}Use ComponentPropsWithoutRef<"button"> to extend native elements. Prefer interface for public component APIs; use type for unions and utility compositions.
strict in tsconfig.json. Use satisfies for config objects that must infer narrow literals while checking shape.32Typing hooks, generics, and discriminated unions
List<T>). Model async UI state with discriminated unions so TypeScript narrows fields correctly in each branch.type AsyncState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: string };
interface User {
id: string;
name: string;
}
function useUser(userId: string): AsyncState<User> {
const [state, setState] = useState<AsyncState<User>>({ status: "idle" });
useEffect(() => {
setState({ status: "loading" });
fetchUser(userId)
.then((data) => setState({ status: "success", data }))
.catch((err: unknown) =>
setState({
status: "error",
error: err instanceof Error ? err.message : "Unknown error",
})
);
}, [userId]);
return state;
}
function UserCard({ userId }: { userId: string }) {
const state = useUser(userId);
switch (state.status) {
case "idle":
case "loading":
return <p>Loading…</p>;
case "error":
return <p role="alert">{state.error}</p>;
case "success":
return <h2>{state.data.name}</h2>; // `data` is narrowed to User
}
}
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
keyExtractor: (item: T) => string;
}
function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
return <ul>{items.map((item) => <li key={keyExtractor(item)}>{renderItem(item)}</li>)}</ul>;
}For context, use createContext<T | null>(null) and a type guard in the consumer hook. For useReducer, type actions as a discriminated union and infer state from the reducer return type.
@types/react and @types/react-dom versions matching your React major version. Run tsc --noEmit in CI to prevent prop drift.useFetch<T>(url) hook returning AsyncState<T>. Build a List<User> that only compiles when renderItem receives a User. Intentionally access data in the error branch and fix the compiler error with proper narrowing.
*End of React Learning Notes — 32 lessons from JSX fundamentals through React 19 and TypeScript patterns. Next steps: build a small project (todo app → dashboard with routing and data fetching), then explore a meta-framework (Next.js or Remix) and a headless component library (Radix UI).*