Skip to content
Tutorials Center
My learning

Topics

Lesson 127 of 132 ยท Practice and Review

React Cheat Sheet

A compact React 19 cheat sheet with runnable examples - JSX rules, props, every hook in one table, state update patterns, Effect rules, form actions and the newest React 19 features.

This page is the one to keep open in a tab. It is not a replacement for the lessons; each section links to the lesson that explains the idea in full. Think of it as a map: you will already know most of what is on it, and when you do not, you will know where to read. The examples are short and runnable, so you can change them and see what happens.

Everything here targets React 19. If you work on an older codebase you will see class components, forwardRef, ReactDOM.render and <Context.Provider>; they still work in many places, but new code should use the modern forms shown below.

JSX rules at a glance

Rule Example
One root element (or a fragment) <>...</>
Close every tag <img src="a.png" alt="" />
class becomes className, for becomes htmlFor <label htmlFor="name">
Attributes are camelCase onClick, tabIndex, readOnly
{} holds any JavaScript expression, not statements {count + 1}, {items.length > 0 && ...}
style takes an object style={{ marginTop: 8 }}
Components start with a capital letter <UserCard />
Lists need a stable key among siblings <li key={user.id}>
Never put 0 on the left of && {count > 0 && ...}, not {count && ...}

See JSX basics, JSX in depth, conditional rendering and lists and keys.

JSX, props and list recipes

Notice "Wrong: 0": a number is a valid thing to render, so 0 && ... renders 0. A boolean comparison renders nothing. Fragment with a key is the only way to give a key to a group of elements without a wrapper node.

Components and props

  • A component is a function that takes one props object and returns what to render. Name it in PascalCase.
  • Props are read-only. To change what a child shows, the parent passes different props.
  • Destructure with defaults in the parameter list: function Button({ kind = 'primary', children }).
  • children is just a prop. Pass any JSX between the tags.
  • A component must be pure: same props, state and context in, same JSX out, with no changes to anything created before the render (pure components).
  • Define components at the top level of a module. A component defined inside another component is a new type on every render and loses its state.

More: components, props, children and composition.

Every hook in one table

Hook Use it for Lesson
useState Values that change and must re-render useState
useReducer Many related updates, named actions reducers
useContext / use(Context) Reading shared values without prop drilling context
useRef Mutable value that does not render, DOM nodes useRef
useEffect Synchronizing with an external system useEffect
useLayoutEffect Measuring the DOM before the browser paints other hooks
useEffectEvent Reading the latest props/state inside an Effect without re-running it useEffectEvent
useMemo Caching an expensive calculation useMemo and useCallback
useCallback Keeping a function's identity stable useMemo and useCallback
useTransition Marking an update as non-urgent, isPending transitions
useDeferredValue A lagging copy of a fast-changing value transitions
use Reading a promise (with Suspense) or context use and Suspense
useActionState State and pending flag for a form action useActionState
useFormStatus A child reading its parent form's pending state useFormStatus and useOptimistic
useOptimistic Showing the expected result while an action runs useFormStatus and useOptimistic
useId Unique ids for accessibility attributes other hooks
useSyncExternalStore Subscribing to a store outside React external stores
useImperativeHandle Exposing a small imperative API through a ref refs and imperative handles

Rules of Hooks: call hooks only at the top level of a component or custom hook (never in loops, conditions or after an early return), and only from React functions. Custom hooks start with use. (Rules of Hooks, custom hooks.) The use function is the one exception: it may be called inside conditions and loops.

State patterns

State is a snapshot: inside one render every variable has one fixed value, even after you call a setter. Setters schedule the next render.

Goal Pattern
Replace a value setCount(5)
Compute from the previous value setCount((c) => c + 1)
Update an object setUser({ ...user, name: 'Ada' })
Update a nested object setUser({ ...user, address: { ...user.address, city } })
Add to an array setItems([...items, newItem])
Remove from an array setItems(items.filter((item) => item.id !== id))
Change one item setItems(items.map((item) => (item.id === id ? { ...item, done: true } : item)))
Expensive first value useState(() => computeInitial())
Reset a component's state Give it a different key
Same value again React bails out and skips the render

Never mutate state (items.push(x), user.name = 'Ada'): React compares by reference, so a mutated object looks unchanged. Do not store what you can calculate: derive totals, filtered lists and "is empty" flags during render. Share state by lifting it to the closest common parent (lifting state up, state updates, objects and arrays).

State update recipes

Press the first button: it adds only 1, because all three calls read the same count snapshot. The second button uses updater functions, which queue up and add 3. remaining is calculated during render and never stored.

Effect rules

An Effect synchronizes your component with a system outside React: a timer, a subscription, a browser API, a non-React widget. If there is no external system, you probably do not need an Effect (you might not need an Effect).

  1. Run an Effect because the component appeared on screen or a value it uses changed, never because a click happened. Clicks belong in event handlers.
  2. List every reactive value the Effect reads (props, state, values derived from them) in the dependency array. The linter checks this for you (effect dependencies).
  3. [] means "only after mount"; omitting the array means "after every render".
  4. Return a cleanup function that undoes the setup: clear the timer, remove the listener, close the connection. React runs it before the next run and on unmount (effect cleanup).
  5. Do not fix a dependency warning by lying in the array. Move code into the Effect, change the logic, or use useEffectEvent for values that should not re-trigger it.
  6. In development, <StrictMode> runs setup, cleanup, setup once on mount. If that breaks your component, your cleanup is incomplete.
Effect with cleanup under StrictMode

In the console panel you will see setup, step 1, then cleanup, step 1, then setup, step 1 again: that is StrictMode's extra mount check, and exactly one interval stays alive because the cleanup cleared the first. Press the button and you will see cleanup, step 1 followed by setup, step 2: the old Effect is torn down before the new one starts.

Refs, memoization and performance

  • useRef(initial) returns { current }. Changing current does not re-render. Use it for DOM nodes (ref={inputRef}), timer ids and other values the screen does not show. Never read or write ref.current during render.
  • React re-renders a component when its state changes, when its parent renders, or when a context it reads changes. Re-rendering is not the same as touching the DOM; React only commits real differences.
  • Measure before optimizing (profiling). Then, in this order: move state down, pass children as props, memo for expensive pure children (memo), useMemo for slow calculations, virtualize long lists (virtualization).
  • The React Compiler can add much of this memoization automatically (React Compiler).

Common recipes

Need Recipe
Controlled input value={text} onChange={(e) => setText(e.target.value)}
Form submit onSubmit={(e) => { e.preventDefault(); ... }} on <form>
Toggle setOpen((o) => !o)
Focus on mount or click const ref = useRef(null) then ref.current.focus()
Unique label ids const id = useId() then htmlFor={id}
Run code once per prop change Effect with that prop in the dependency array
Loading and error UI Suspense + error boundary, or status state
Modal outside the DOM tree createPortal(children, document.body) (portals)
Catch render errors An error boundary (error boundaries)
Share a value deeply <ThemeContext value={theme}> and use(ThemeContext)
Debounce A custom hook with setTimeout and cleanup

What React 19 added

These are the changes that shape new code:

  • Actions. A <form action={fn}> accepts a function, sync or async. React wraps it in a transition, resets uncontrolled fields after it succeeds, and gives you FormData.
  • useActionState(action, initial) returns [state, formAction, isPending]; the action receives the previous state and the form data.
  • useOptimistic(value, reducer) shows a temporary value while an action is pending and snaps back to the real value afterwards.
  • useFormStatus() lets a button deep inside a form read { pending } without props.
  • use(promiseOrContext) reads a promise (suspending until it settles) or a context, even after an early return.
  • ref is a normal prop for function components, so forwardRef is no longer needed. Ref callbacks may return a cleanup function.
  • <Context value> replaces <Context.Provider value>.
  • Document metadata: <title>, <meta> and <link> rendered anywhere in the tree are hoisted into <head>.
  • useEffectEvent (stable in 19.2) for non-reactive logic inside Effects.
Form actions, useActionState and useOptimistic

Both forms are uncontrolled: React hands the action a FormData, and clears the fields when the action finishes. In Notes, the new entry appears at once with "(sending...)", then the real value replaces it when setNotes runs.

ref as a prop, Context value and metadata

The input component receives ref like any other prop. The context is provided with <ThemeContext value="dark">. The <title> element is hoisted: look at the browser tab (or document.title) and you will see "Cheat sheet demo". The ref callback returns a cleanup function, so the console shows attached DIV on mount and detached when you hide the box.

Quick reference for what lives where

  • Server Components and 'use server' need a framework such as Next.js; they cannot run in a plain browser module (server components).
  • Routing, data caching and forms at scale usually come from libraries: React Router, TanStack Query or SWR, a form library (ecosystem).
  • TypeScript adds types to props, state and events without changing runtime behavior (TypeScript with React).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does {count && <Badge />} display a 0 on the screen when count is 0?

    The && operator returns the left side when it is falsy. React skips false, null and undefined, but 0 is a number and is rendered. Use count > 0 && ... instead.
  2. 2. setCount(count + 1) is called three times in one click handler, starting from 0. What is count after the render?

    All three calls read the same snapshot (count is 0 in that render), so each one schedules 'set to 1'. Updater functions such as setCount(c => c + 1) would give 3.
  3. 3. Which belongs in an Effect rather than an event handler?

    Effects synchronize a component with an external system for as long as it is displayed. Reactions to a specific user action belong in event handlers.
  4. 4. What is true about the ref prop in React 19 function components?

    React 19 passes ref as an ordinary prop to function components, so forwardRef is not needed in new code. Callback refs may return a cleanup function.
  5. 5. What does useOptimistic do when the surrounding action finishes?

    The optimistic value is a temporary layer over the real state. When the action completes, React discards the layer and shows whatever the real state now is.

Summary

  • JSX returns one root, uses camelCase attributes and className, and renders 0 if you write 0 && ...; keys belong on the outermost element in a list.
  • Props are read-only; components are pure functions defined at module level.
  • Hooks follow the Rules of Hooks; use the hook table to pick the right one (useState first, useReducer for many actions, useRef for values that do not render).
  • Treat state as an immutable snapshot: use updater functions for sequential changes and copy objects and arrays; derive everything you can.
  • Effects synchronize with outside systems, list all dependencies, and clean up after themselves.
  • React 19 adds form actions, useActionState, useOptimistic, useFormStatus, use, ref as a prop, <Context value> and hoisted metadata.

Next: Common React Mistakes and How to Fix Them