ReReact · Lesson 8 of 8

React Cheatsheet

Components, hooks, and patterns on one page.

JSX
// ── Components & JSX ────────────────────
function Card({ title, children, onClose }) {
  return (
    <div className="card">
      <h2>{title}</h2>
      {children}
      <button onClick={onClose}>×</button>
    </div>
  );
}
<Card title="Hi">body</Card>

// Conditional & list rendering:
{isOpen && <Modal />}
{user ? <Profile /> : <Login />}
{items.map(item => <Row key={item.id} {...item} />)}

// ── State ───────────────────────────────
const [count, setCount] = useState(0);
setCount(c => c + 1);              // updater form for math
const [form, setForm] = useState({ name: "", email: "" });
setForm(f => ({ ...f, name: "Ada" }));   // never mutate

// ── Effects ─────────────────────────────
useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id);  // cleanup
}, []);                            // [] = run once on mount
useEffect(() => { ... }, [dep]);   // re-run when dep changes
JSX
// ── More hooks ──────────────────────────
const ref = useRef(null);              // DOM handle / mutable box
const memo = useMemo(() => expensive(x), [x]);
const cb = useCallback(() => save(id), [id]);
const value = useContext(ThemeContext);
const [state, dispatch] = useReducer(reducer, initial);

// ── Context ─────────────────────────────
const ThemeContext = createContext("light");
<ThemeContext.Provider value="dark">...</ThemeContext.Provider>

// ── Controlled forms ────────────────────
<input
  value={text}
  onChange={e => setText(e.target.value)}
/>
<form onSubmit={e => { e.preventDefault(); submit(); }}>

// ── Rules & patterns ────────────────────
// hooks only at the top level, never in if/loops
// key must be stable & unique — not the array index
// state is a snapshot; effects sync with EXTERNAL systems
// derive what you can: don't mirror props into state
// lift state up to the closest common parent