React Hooks Basics
11 examples to get you started with React Hooks -- 7 basic and 4 intermediate.
Search across all documentation pages
11 examples to get you started with React Hooks -- 7 basic and 4 intermediate.
🤖 Read the SystemsArchitect.io Blog for over 100+ cloud architecture articles 🔥
Hooks ship with React itself -- no extra dependencies required. A TypeScript React project (Next.js, Vite, or CRA) is enough to run every example below.
# If you do not already have a project:
npx create-next-app@latest my-app --typescript --tailwind --app
cd my-app
npm run devTwo rules apply to every hook on this page:
Store a value that triggers a re-render whenever it changes.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount((c) => c + 1)}>
Count: {count}
</button>
);
}useState returns a [value, setter] pair.(c) => c + 1) when the new value depends on the previous one -- it avoids stale closures.useState(0) is the initial value, used only on first render.Related: useState -- updater functions, lazy init, batching | Typing State -- typing complex state shapes
Run a side effect after render -- subscribing, timing, or touching non-React APIs.
import { useEffect, useState } from "react";
function Clock() {
const [now, setNow] = useState(() => new Date());
useEffect(() => {
const id = setInterval(() => setNow(new Date()), 1000);
return () => clearInterval(id);
}, []);
return <p>{now.toLocaleTimeString()}</p>;
}[] means "run once on mount"; listing variables means "re-run when any of them change".useEffect for data you can fetch in a Server Component -- it causes waterfalls and loading flicker.Related: useEffect -- cleanup, dependency arrays, common mistakes | SWR Basic Fetching -- prefer this for client-side data
Hold a value across renders without triggering a re-render, or reference a DOM node.
import { useEffect, useRef } from "react";
function AutoFocusInput() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} placeholder="Auto-focused" />;
}useRef returns a { current } object that persists across renders.ref.current does not trigger a re-render -- unlike state.ref prop to get a handle to the underlying DOM element.Related: useRef -- ref patterns, forwarding, callback refs | Typing Refs -- ref types for elements and instances
Read a context value anywhere in the tree without prop drilling.
import { createContext, useContext } from "react";
const ThemeContext = createContext<"light" | "dark">("light");
function ThemedLabel() {
const theme = useContext(ThemeContext);
return (
<span className={theme === "dark" ? "text-white" : "text-black"}>Hi</span>
);
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedLabel />
</ThemeContext.Provider>
);
}useContext subscribes the component to the context -- it re-renders whenever the provider's value changes."light" here) is used only when no matching provider is above in the tree.Related: useContext -- providers, default values, splitting contexts | Context Patterns -- when and how to split contexts | Context vs. Zustand -- choosing between them
Manage complex state transitions with action-based updates.
import { useReducer } from "react";
type Action = { type: "increment" } | { type: "decrement" } | { type: "reset" };
function reducer(state: number, action: Action): number {
switch (action.type) {
case "increment":
return state + 1;
case "decrement":
return state - 1;
case "reset":
return 0;
}
}
function Counter() {
const [count, dispatch] = useReducer(reducer, 0);
return (
<div>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<span>{count}</span>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</div>
);
}useReducer when state has multiple related fields or complex transitions that would span many useState calls.dispatch calls.useState calls in one component, consider useReducer instead.Related: useReducer -- action patterns, lazy init, nested state | Discriminated Unions -- type-safe action shapes
Memoize an expensive computation so it only re-runs when its inputs change.
import { useMemo, useState } from "react";
function ProductList({ products }: { products: { id: number; price: number }[] }) {
const [filter, setFilter] = useState("");
const total = useMemo(
() => products.reduce((sum, p) => sum + p.price, 0),
[products]
);
return (
<div>
<input value={filter} onChange={(e) => setFilter(e.target.value)} />
<p>Total: ${total}</p>
</div>
);
}useMemo recomputes the value only when dependencies change, skipping work on unrelated re-renders.useMemo adds code overhead without perf gain.useMemo calls become unnecessary -- the compiler memoizes automatically.Related: useMemo -- when memoization actually helps | React Compiler -- auto-memoization in React 19 | Memoization -- broader perf patterns
Memoize a function reference so it stays stable across renders.
import { useCallback, useState } from "react";
function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {
return <input onChange={(e) => onSearch(e.target.value)} />;
}
function App() {
const [query, setQuery] = useState("");
const handleSearch = useCallback((q: string) => {
setQuery(q);
}, []);
return (
<>
<SearchBox onSearch={handleSearch} />
<p>Query: {query}</p>
</>
);
}useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).React.memo) or listing it as a dependency in useEffect.useMemo, avoid premature use -- the React Compiler handles most cases in React 19.Related: useCallback -- patterns and pitfalls | useMemo -- sibling primitive | Re-renders -- when callback identity matters
Extract stateful logic into a reusable function.
import { useEffect, useState } from "react";
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(() =>
typeof navigator === "undefined" ? true : navigator.onLine
);
useEffect(() => {
const on = () => setIsOnline(true);
const off = () => setIsOnline(false);
window.addEventListener("online", on);
window.addEventListener("offline", off);
return () => {
window.removeEventListener("online", on);
window.removeEventListener("offline", off);
};
}, []);
return isOnline;
}
function StatusBanner() {
const isOnline = useOnlineStatus();
return <p>You are {isOnline ? "online" : "offline"}</p>;
}use and may call other hooks.navigator, window) need guards for the server render.Related: Custom Hooks -- rules, testing, patterns | Custom Hooks Guide -- broader patterns | useToggle -- a real-world custom hook
Mark a state update as non-urgent so the UI stays responsive.
import { useState, useTransition } from "react";
function FilterableList({ items }: { items: string[] }) {
const [query, setQuery] = useState("");
const [filtered, setFiltered] = useState(items);
const [isPending, startTransition] = useTransition();
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setQuery(e.target.value);
startTransition(() => {
setFiltered(items.filter((i) => i.includes(e.target.value)));
});
};
return (
<div>
<input value={query} onChange={handleChange} />
{isPending && <p>Updating...</p>}
<ul>
{filtered.map((i) => (
<li key={i}>{i}</li>
))}
</ul>
</div>
);
}startTransition are low priority -- React can interrupt them if the user types again.isPending lets you show a subtle loading indicator during the deferred work.<form action={...}> submissions in a transition automatically -- no explicit startTransition needed for form actions.Related: useTransition -- patterns and pitfalls | useDeferredValue -- sibling hook for deferring a value rather than an update
Drive a form action and track its pending state and result in one call.
"use client";
import { useActionState } from "react";
async function submitFeedback(_prev: string | null, formData: FormData) {
const message = formData.get("message") as string;
if (!message) return "Message is required.";
await fetch("/api/feedback", { method: "POST", body: formData });
return null;
}
function FeedbackForm() {
const [error, action, isPending] = useActionState(submitFeedback, null);
return (
<form action={action}>
<textarea name="message" />
{error && <p>{error}</p>}
<button type="submit" disabled={isPending}>
{isPending ? "Sending..." : "Send"}
</button>
</form>
);
}[state, action, isPending] -- wire the action directly to <form action={action}>.FormData; its return value becomes the next state.useFormState -- same API, new name.Related: useActionState -- full API and patterns | Server Actions -- the server side of the pair | Server Action Forms -- end-to-end form patterns
Read a promise or context inline -- no .then, no useEffect.
"use client";
import { Suspense, use } from "react";
interface User {
id: number;
name: string;
}
function UserCard({ userPromise }: { userPromise: Promise<User> }) {
const user = use(userPromise);
return <h2>{user.name}</h2>;
}
function UserPage({ userPromise }: { userPromise: Promise<User> }) {
return (
<Suspense fallback={<p>Loading...</p>}>
<UserCard userPromise={userPromise} />
</Suspense>
);
}use(promise) suspends the component until the promise resolves -- the parent <Suspense> shows the fallback.use(context) reads a context value and, unlike useContext, can be called conditionally inside if blocks.useEffect data fetching story.Related: use -- full API details | Suspense -- the fallback mechanism | Server Components -- where promises usually originate
Reviewed by Chris St. John·Last updated Jul 19, 2026
🤖 Read the SystemsArchitect.io Blog for over 100+ cloud architecture articles 🔥