React Cheat Sheet
Quick reference from FreeCodingCourses.com
Components and JSX
function Hello() { return <h1>Hi</h1> }- a component is a function that returns JSX.
<Hello />- use it like an HTML tag. Component names are capitalized.
<div className="card">- class is className in JSX.
<p>{2 + 2}</p>- curly braces drop JavaScript into JSX.
return <>{a}{b}</>- a fragment groups siblings without a wrapper div.
Props
function Card({ title, children }) { ... }- props come in as one object; destructure them.
<Card title="Hello" count={3} />- strings in quotes, everything else in braces.
<Card>text</Card> // props.children- content between tags is children.
function Card({ title = 'Untitled' })- default value for a missing prop.
State with useState
const [count, setCount] = useState(0)- state value plus its setter, initial value 0.
setCount(count + 1)- update; React re-renders the component.
setCount(c => c + 1)- functional update, safest when the new value depends on the old.
const [user, setUser] = useState(null)- state can hold anything: object, array, null.
Effects with useEffect
useEffect(() => { ... }, [])- run once after first render (empty deps).
useEffect(() => { ... }, [id])- re-run whenever id changes.
useEffect(() => { return () => cleanup() }, [])- return a cleanup function.
// fetch, subscriptions, timers go here- effects are for talking to the outside world.
Lists and keys
{items.map(i => <li key={i.id}>{i.name}</li>)}- render a list with map.
key={i.id}- a stable, unique key per item. Not the array index if the list changes.
{loading && <Spinner />}- render conditionally with &&.
{ok ? <Yes /> : <No />}- either/or with a ternary.
Events and forms
<button onClick={handleClick}>- pass the function, do not call it.
<input value={name} onChange={e => setName(e.target.value)} />- controlled input tied to state.
<form onSubmit={e => { e.preventDefault(); ... }}>- stop the page reloading on submit.
Gotchas worth knowing
- •Never mutate state directly. Call the setter. For objects and arrays, make a new copy: setUser({ ...user, age: 37 }).
- •Every item in a mapped list needs a stable key prop. Use a real id, not the array index, or React can mix up rows when the list changes.
- •onClick={handleClick} passes the function; onClick={handleClick()} calls it during render, which is a common bug.
- •If useEffect runs too often or loops, check its dependency array. Missing deps cause stale values; wrong deps cause extra runs.