Cheat sheet · Front end
React cheat sheet
Components, props, state, effects and the hooks you use in nearly every React app.
- Sections
- 5
- Items
- 22
- Area
- Front end
- Download
- PNG, PDF
Cheat sheet
React
Components, props, state, effects and the hooks you use in nearly every React app.
Components and JSX
function Card({ title }) { return <h2>{title}</h2> }- A component: a function that returns JSX
<Card title="Hi" />- Use it, passing props
className="box"- Use className, not class
<>...</>- A fragment: group items with no extra element
{cond && <A />}- Show A only when cond is true
{cond ? <A /> : <B />}- Choose between two
{items.map(i => <li key={i.id}>{i.name}</li>)}- A list: each item needs a stable key
State
const [n, setN] = useState(0)- A value that re-renders the screen when it changes
setN(n + 1)- Set a new value
setN(prev => prev + 1)- Set from the latest value (safer)
const [state, dispatch] = useReducer(fn, init)- State with named actions
Effects
useEffect(() => { ... }, [])- Run once after the first render
useEffect(() => { ... }, [id])- Run again whenever id changes
return () => { ... }- Clean up inside an effect (timers, listeners)
More hooks
const ref = useRef(null)- A box that survives renders; also holds a DOM element
const v = useMemo(() => calc(a), [a])- Remember an expensive result
const f = useCallback(() => { }, [a])- Remember a function
const theme = useContext(ThemeContext)- Read a value shared by a parent
memo(Component)- Skip re-rendering when the props are the same
Events and forms
<button onClick={() => save()}>- Run code on a click
<input value={v} onChange={e => setV(e.target.value)} />- A controlled input
<form onSubmit={e => { e.preventDefault(); }}>- Handle a form without a page reload
Remember
- Hooks rules: call them at the top level of a component, never inside if, loops or after a return.
- Do not change state or props directly. Make a new array or object instead.
- If you can work a value out from state or props, do not store it in state.
Learn it properly
A cheat sheet helps you remember. These lessons explain the ideas step by step, with examples.