React API Reference & Cheatsheet
A comprehensive React API reference for every hook, pattern, and utility — use it as a quick lookup when building production React apps at DodaTech.
What You’ll Learn
- Every React hook and when to use it
- JSX rules, component types, and event handling patterns
- Context API, refs, portals, and code splitting syntax
- Performance optimization with memo, useMemo, and useCallback
- Vite and ESLint configuration for React projects
Why a React Reference Matters
Even experienced developers can’t memorize every API signature. A well-organized reference keeps you in the flow without tab-switching to documentation. At DodaTech, this covers the exact patterns we use in Durga Antivirus Pro (data-heavy dashboards) and DodaZIP (file manager UI).
Your Learning Path
flowchart LR
A[React Basics] --> B[React Hooks]
B --> C[React Advanced]
C --> D[React Reference]
D --> E[Next.js]
D --> F[React Native]
style D fill:#3b82f6,color:#fff,stroke:#2563eb,stroke-width:3px
Installation & Setup
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev # http://localhost:5173
npm run build # production buildJSX Rules
return <div>Hello</div>; // Single root element (or Fragment)
return <>Hello</>; // Fragment — no extra DOM node
const el = <h1>{name}</h1>; // Embed JS expressions with {}
const cls = <div className="box" />; // class → className
const sty = <div style={{ color: "red" }} />; // Inline styles as objectComponent Types
// Function component (modern, preferred)
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
// Arrow function with default props
const Button = ({ variant = "primary", children }) => (
<button className={`btn-${variant}`}>{children}</button>
);Hooks Reference
| Hook | Purpose | Returns |
|---|---|---|
useState(init) | Local component state | [value, setter] |
useEffect(fn, deps) | Side effects (API, timers, listeners) | — |
useContext(ctx) | Read context value | context value |
useRef(init) | Mutable value, no re-renders | { current: init } |
useReducer(red, init) | Complex state with centralized reducer | [state, dispatch] |
useMemo(fn, deps) | Cached computed value | computed value |
useCallback(fn, deps) | Stable function reference | memoized fn |
useLayoutEffect(fn, deps) | Sync effect before paint | — |
useId() | Unique IDs for a11y (React 18) | string |
useTransition() | Low-priority state updates (React 18) | [pending, start] |
useDeferredValue(val) | Deferred re-rendering (React 18) | deferred value |
useImperativeHandle(ref, fn) | Expose custom methods via ref | — |
useDebugValue(val) | Custom label in React DevTools | — |
useEffect Dependency Patterns
useEffect(fn) // Every render (rarely useful)
useEffect(fn, []) // Mount only, cleanup on unmount
useEffect(fn, [dep]) // Mount + when dep changes
useEffect(() => { // With cleanup function
return () => cleanup();
}, []);Event Handling
<button onClick={handler}> // No params
<button onClick={() => handler(id)}> // With params
<form onSubmit={e => e.preventDefault()} />Conditional Rendering
{isLoggedIn ? <Dashboard /> : <Login />}
{user && <p>Welcome, {user.name}</p>}
{!loading || <Spinner />}Lists & Keys
{items.map(item => <Item key={item.id} {...item} />)}Forms (Controlled Components)
function Form() {
const [value, setValue] = useState("");
const handleSubmit = (e) => { e.preventDefault(); console.log(value); };
return (
<form onSubmit={handleSubmit}>
<input value={value} onChange={e => setValue(e.target.value)} />
</form>
);
}Context API
const Ctx = createContext(defaultValue);
<Ctx.Provider value={val}>...</Ctx.Provider>
const val = useContext(Ctx);Refs
const ref = useRef(null);
<input ref={ref} />;
ref.current.focus();
// forwardRef to child component
const Fancy = forwardRef((props, ref) => <input ref={ref} />);Error Boundary
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError(error) { return { hasError: true }; }
componentDidCatch(error, info) { /* log error */ }
render() { return this.state.hasError ? <Fallback /> : this.props.children; }
}Portals
import { createPortal } from "react-dom";
createPortal(<Modal />, document.body);Code Splitting
import { lazy, Suspense } from "react";
const Dashboard = lazy(() => import("./Dashboard"));
<Suspense fallback={<Spinner />}><Dashboard /></Suspense>Performance
// Memoize component — only re-renders when props change
const MemoList = memo(({ items }) => items.map(...));
// Memoize value — only recomputes when deps change
const sorted = useMemo(() => items.sort(), [items]);
// Memoize function — stable reference across renders
const cb = useCallback((id) => handleClick(id), [handleClick]);
// Custom comparison for React.memo
const MyComponent = React.memo(Component, (prev, next) => {
return prev.id === next.id; // Only re-render if id changes
});useMemo vs useCallback
| Feature | useMemo | useCallback |
|---|---|---|
| Returns | A cached value | A cached function |
| Syntax | useMemo(() => expr, deps) | useCallback(fn, deps) |
| Equivalent | — | useMemo(() => fn, deps) |
| Use case | Expensive computations | Stable callbacks for memoized children |
HOC Pattern
function withFeature(Wrapped) {
return function Enhanced(props) {
const extraProp = useSomeHook();
return <Wrapped {...props} {...extraProp} />;
};
}Common Imports
import {
useState, useEffect, useContext, useRef,
useReducer, useMemo, useCallback, useId,
createContext, createRef, forwardRef,
lazy, Suspense, memo, Fragment,
createPortal, StrictMode, startTransition,
} from "react";
import { createRoot } from "react-dom/client";Vite Config for React
// vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({ plugins: [react()] });ESLint Config for React Hooks
{
"extends": ["react-app"],
"plugins": ["react-hooks"],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
}Common Mistakes
1. Wrong import path for hooks
import { useState } from "react-dom" is wrong. Hooks come from the react package, not react-dom.
2. Forgetting that useState replaces (doesn’t merge) objects
setUser({ name: "Alice" }); // email is lost!
setUser(prev => ({ ...prev, name: "Alice" })); // ✅ merge with spread3. Inconsistent dependency arrays
If the number of deps changes between renders, React throws an error. Keep the count stable.
4. Using regular variables instead of useState
let count = 0; // Resets on every render, no re-renderUse useState for values that affect the UI.
5. Calling hooks outside a React component
Hooks can only be called from React function components or custom hooks.
6. Using createRoot incorrectly (React 18)
// ❌ Old way (React 17)
ReactDOM.render(<App />, document.getElementById("root"));
// ✅ React 18 way
createRoot(document.getElementById("root")).render(<App />);Practice Questions
What is the difference between
useEffectanduseLayoutEffect?useEffectruns asynchronously after paint.useLayoutEffectruns synchronously before paint. UseuseLayoutEffectonly for reading layout or preventing visual flicker.What does
useId()return?A unique string stable across renders and SSR. Useful for accessible
idattributes on form inputs and ARIA labels.What is
useTransitionused for?It marks a state update as low priority, letting React interrupt it for urgent updates (like typing) to keep the UI responsive.
How does
React.memodiffer fromuseMemo?React.memomemoizes a component’s rendered output (skips re-render).useMemomemoizes a function’s return value (skips recomputation).What is the correct React 18 render method?
createRoot(document.getElementById("root")).render(<App />)fromreact-dom/client.
Challenge
Build a minimal reference card component that dynamically displays hook signatures based on user selection. Each card shows the hook name, parameters, return type, and a one-line code example.
FAQ
Try It Yourself
Explore the major hooks and APIs in this interactive React sandbox:
What’s Next
| Lesson | Description |
|---|---|
| Next.js Full-Stack React | Server rendering, file-based routing, API routes |
| React Native Mobile Apps | Build iOS and Android apps with React |
| TypeScript for React | Type-safe hooks, components, and patterns |
| Node.js Backend for React | Express.js APIs, authentication, databases |
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro