React Cheat Sheet
Setup
// create and run a project
npm create vite@latest app -- --template react
npm install && npm run dev
npm install react-router-dom axios
Components and JSX
export default function Card({ title, children }) { return <div className="card"><h3>{title}</h3>{children}</div>; }
<Card title="Hi"><p>Body</p></Card>
<>{cond ? <A /> : <B />}{list.length > 0 && <List />}</>
{items.map((it) => <li key={it.id}>{it.name}</li>)}
<div style={{ color: "red" }} className={active ? "on" : ""} />
State and events
const [count, setCount] = useState(0);
setCount((c) => c + 1);
setObj({ ...obj, key: value }); setArr([...arr, item]);
<button onClick={() => doThing(id)}>Go</button>
<input value={v} onChange={(e) => setV(e.target.value)} />
<form onSubmit={(e) => { e.preventDefault(); }}></form>
Hooks
useEffect(() => { const id = setInterval(tick, 1000); return () => clearInterval(id); }, []);
const ref = useRef(null); ref.current.focus();
const total = useMemo(() => expensive(items), [items]);
const onSave = useCallback(() => save(id), [id]);
const value = useContext(MyContext);
const [state, dispatch] = useReducer(reducer, initialState);
Router
<BrowserRouter><Routes><Route path="/" element={<Home />} /><Route path="/p/:id" element={<Post />} /></Routes></BrowserRouter>
<Link to="/about">About</Link> <NavLink to="/docs">Docs</NavLink>
const { id } = useParams(); const navigate = useNavigate(); navigate("/login");
Data fetching
useEffect(() => { fetch(url).then((r) => r.json()).then(setData).catch(setError); }, [url]);
const { data } = await axios.get("/api/items");
const Page = lazy(() => import("./Page.jsx"));
Full React documentation