React Cheat Sheet
8 groups · 36 topics · Updated
React is a JavaScript library for building user interfaces out of components. The examples are written for React 19, with function components and Hooks.
Basics
Components, JSX and passing data in.
Start a project
npx create-next-app@latest
npx create-react-router@latest
npm create vite@latest my-app \
-- --template react| Tool | Gives you |
|---|---|
| Next.js | A full framework: routing, server rendering, data loading |
| React Router | Routing, and a full framework when paired with Vite |
| Vite | A fast, minimal set-up with no framework |
A component
function Welcome() {
return <h1>Hello, world</h1>;
}
export default function App() {
return <Welcome />;
}- A component is a function that returns markup.
- Its name starts with a capital letter. Lowercase tags are HTML.
- It returns one root element. Use
<>...</>to group without an extra<div>.
JSX
<>
<img src={url} alt="Logo" />
<label htmlFor="name">Name</label>
<p className="note">{count * 2}</p>
<p style={{ color: "red" }}>Stop</p>
</>| HTML | JSX |
|---|---|
class |
className |
for |
htmlFor |
onclick, tabindex |
onClick, tabIndex |
<br>, <img> |
<br />, <img /> |
style="color: red" |
style={{ color: "red" }} |
- Curly braces hold any JavaScript expression.
Props
function Greeting({ name, size = "md" }) {
return <p className={size}>Hi, {name}</p>;
}<Greeting name="Asha" />
<Greeting name="Ben" size="lg" />- Props are the inputs of a component, passed like attributes.
- They are read-only. A component never changes its own props.
- Text needs quotes. Everything else needs braces:
count={3}.
Children
function Card({ children }) {
return (
<div className="card">{children}</div>
);
}
<Card>
<h2>Title</h2>
<p>Any content goes here.</p>
</Card>- Whatever sits between the tags arrives as the
childrenprop.
Conditions
{isLoggedIn ? <Dashboard /> : <Login />}
{hasError && <p>Something went wrong</p>}
{count > 0 && <Badge count={count} />}if (!user) {
return <p>Loading…</p>;
}
return <Profile user={user} />;{count && <Badge />}shows a0when the count is zero. Compare it instead.
Lists
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>- Every item needs a
keythat is unique among its siblings and does not change. - Use an id from your data. The array index breaks when items are added, removed or reordered.
State and events
Remembering things, and reacting to the user.
useState
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const add = () => setCount(count + 1);
return (
<button onClick={add}>
Clicked {count} times
</button>
);
}useStatereturns the current value and a function to change it.- Changing state makes React run the component again and update the page.
- Each copy of a component has its own state.
Update state
// from the previous value
setCount((c) => c + 1);
// an object: copy, then change
setUser({ ...user, name: "Asha" });
// an array: add, remove, change
setItems([...items, newItem]);
setItems(items.filter((i) => i.id !== id));
setItems(
items.map((i) =>
i.id === id ? { ...i, done: true } : i
)
);- Never change state in place.
items.push(x)does not cause an update. - Always pass a new object or array.
Events
function Form() {
function handleSubmit(event) {
event.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Save</button>
</form>
);
}| Event | Fires when |
|---|---|
onClick |
An element is clicked |
onChange |
An input's value changes |
onSubmit |
A form is submitted |
onKeyDown |
A key is pressed |
onFocus, onBlur |
An element gains or loses focus |
- Pass the function:
onClick={save}. WritingonClick={save()}calls it straight away.
Form inputs
const [name, setName] = useState("");
<input
value={name}
onChange={(e) => setName(e.target.value)}
/><input
type="checkbox"
checked={agreed}
onChange={(e) => {
setAgreed(e.target.checked);
}}
/>- With
valueset, the input shows whatever is in state. This is a controlled input.
Share state
function Page() {
const [query, setQuery] = useState("");
return (
<>
<SearchBox
value={query}
onChange={setQuery}
/>
<Results query={query} />
</>
);
}- When two components need the same data, keep the state in their nearest shared parent.
- Pass the value down as a prop, and a function down to change it.
useReducer
function reducer(state, action) {
switch (action.type) {
case "add":
return { count: state.count + 1 };
case "reset":
return { count: 0 };
default:
return state;
}
}
const [state, dispatch] = useReducer(
reducer,
{ count: 0 }
);
dispatch({ type: "add" });- Use it when one piece of state changes in many different ways.
Effects and refs
Reaching outside React: timers, the network and the page itself.
useEffect
useEffect(() => {
document.title = `${count} clicks`;
}, [count]);| Second argument | The effect runs |
|---|---|
| Left out | After every render |
[] |
Once, after the first render |
[a, b] |
After the first render, and when a or b changes |
- List every prop and state value the effect reads.
Clean up
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);- The returned function runs before the effect runs again, and when the component is removed.
- Clean up anything you start: timers, listeners, connections.
Fetch data
useEffect(() => {
let ignore = false;
fetch(`/api/users/${id}`)
.then((res) => res.json())
.then((data) => {
if (!ignore) setUser(data);
});
return () => {
ignore = true;
};
}, [id]);ignorestops an old, slow reply from overwriting a newer one.- A framework or a data library handles caching and loading states better than this.
Skip the effect
| You want to | Do this instead |
|---|---|
| Work a value out from props or state | Calculate it while rendering |
| Respond to a click or a submit | Use the event handler |
| Reset state when a prop changes | Give the component a different key |
| Cache a slow calculation | useMemo |
Effects are for staying in step with something outside React.
useRef
function Search() {
const inputRef = useRef(null);
function focus() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={focus}>Search</button>
</>
);
}- A ref gives direct access to an element on the page.
- It can also hold any value between renders, such as a timer id.
- Changing
ref.currentdoes not cause an update.
Sharing and reuse
Passing data deep, and reusing logic.
Context
const ThemeContext = createContext("light");
function App() {
return (
<ThemeContext value="dark">
<Page />
</ThemeContext>
);
}
function Label() {
const theme = useContext(ThemeContext);
return <p className={theme}>Hello</p>;
}- Context makes a value available to every component below, without passing props through each level.
- Good for the theme, the current user and the language. Not a replacement for all props.
- Before React 19 the wrapper was written
<ThemeContext.Provider>.
Custom Hooks
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = () => setOn((v) => !v);
return [on, toggle];
}
function Menu() {
const [open, toggleOpen] = useToggle();
return (
<button onClick={toggleOpen}>
{open ? "Close" : "Open"}
</button>
);
}- A custom Hook is a function whose name starts with
useand that calls other Hooks. - It shares logic, not state. Each component that calls it gets its own copy.
Rules of Hooks
- Call Hooks only at the top level of a component or a custom Hook.
- Never inside a condition, a loop or a nested function.
- Call them in the same order on every render.
// Wrong
if (isOpen) {
const [value, setValue] = useState("");
}Hooks at a glance
| Hook | For |
|---|---|
useState |
A value that changes |
useReducer |
State with many kinds of update |
useContext |
Reading a context |
useRef |
An element, or a value that does not cause updates |
useEffect |
Staying in step with something outside React |
useMemo |
Caching a calculation |
useCallback |
Caching a function |
useId |
A unique id, for labels and inputs |
useTransition |
Keeping the page responsive during a slow update |
Performance
Doing less work, only where it is needed.
When React renders
A component runs again when:
- its own state changes;
- its parent renders;
- a context it reads changes.
Rendering is usually fast. Measure with the React DevTools profiler before optimising.
useMemo and useCallback
const done = useMemo(
() => items.filter((i) => i.done),
[items]
);
const save = useCallback(() => {
onSave(id);
}, [id, onSave]);useMemokeeps a result until its inputs change.useCallbackkeeps the same function until its inputs change.- If your project uses the React Compiler, it adds this caching for you.
memo
const Row = memo(function Row({ item }) {
return <li>{item.name}</li>;
});- A memoised component is skipped when its props are the same as last time.
- It only helps if the props really are the same: pass stable objects and functions.
Load code later
const Chart = lazy(() => import("./Chart"));
<Suspense fallback={<p>Loading…</p>}>
<Chart />
</Suspense>- The code for
Chartis downloaded only when it is first shown. Suspenseshows the fallback while it loads.
Transitions
const [isPending, startTransition] =
useTransition();
function handleChange(text) {
startTransition(() => {
setQuery(text);
});
}- Marks an update as not urgent, so typing and clicking stay responsive.
isPendingis true while the update is being prepared.
React 19
Features added in version 19.
Form actions
function Signup() {
async function join(formData) {
await addUser(formData.get("email"));
}
return (
<form action={join}>
<input name="email" />
<button>Join</button>
</form>
);
}- A function passed to
actionreceives the form's data when it is submitted. - The form is reset after the action succeeds.
useActionState
async function send(previous, formData) {
const result = await save(formData);
return result.error ?? null;
}
const [error, submit, isPending] =
useActionState(send, null);
<form action={submit}>
<button disabled={isPending}>Save</button>
{error && <p>{error}</p>}
</form>- Gives the result of the last submission, an action to pass to the form, and whether it is running.
use
function Comments({ commentsPromise }) {
const comments = use(commentsPromise);
return (
<ul>
{comments.map((c) => (
<li key={c.id}>{c.text}</li>
))}
</ul>
);
}usereads the value of a promise, or of a context.- While the promise is pending, the nearest
Suspenseshows its fallback. - Unlike a Hook, it may be called inside a condition.
ref as a prop
function TextInput({ ref, ...props }) {
return <input ref={ref} {...props} />;
}
<TextInput ref={inputRef} />- A function component can now receive
reflike any other prop. forwardRefis no longer needed.
Server and client
| Server component | Client component | |
|---|---|---|
| Runs | On the server | In the browser |
| Can read a database or files | Yes | No |
| Can use state, effects, events | No | Yes |
| Marked with | Nothing: the default in a framework | "use client" at the top of the file |
"use client";
import { useState } from "react";- Server components need a framework that supports them, such as Next.js.
Watch out
Mistakes that catch most people once.
Common mistakes
| Mistake | Fix |
|---|---|
items.push(x) on state |
setItems([...items, x]) |
onClick={save()} |
onClick={save} |
The array index as key |
A stable id from the data |
| A value missing from an effect's list | List everything the effect reads |
| An effect to work out a value | Calculate it while rendering |
{count && <Badge />} shows 0 |
{count > 0 && <Badge />} |
A Hook inside an if |
Top level only |
class in JSX |
className |
| A component defined inside another | Define it at the top level of the file |
State is a snapshot
setCount(count + 1);
setCount(count + 1);
// goes up by 1: both saw the same count
setCount((c) => c + 1);
setCount((c) => c + 1);
// goes up by 2- State does not change in the middle of a function. The new value arrives on the next render.
- Reading
countstraight aftersetCountstill gives the old value.
Strict Mode
<StrictMode>
<App />
</StrictMode>- In development only, components render twice and effects run twice.
- It is deliberate: it exposes effects with no clean-up and code that changes things while rendering.
- Nothing is doubled in production.
More help
The official pages to check details against.
Official documentation
| Topic | Page |
|---|---|
| Learning | Learn React |
| Hooks | Built-in React Hooks |
| Effects | You Might Not Need an Effect |
| Starting a project | Creating a React App |
| Everything | React Reference |
See the JavaScript cheat sheet for the language underneath.