Skip to content
React API Reference & Cheatsheet

React API Reference & Cheatsheet

DodaTech Updated Jun 6, 2026 7 min read

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
  
Prerequisites: This is a reference page, not a tutorial. You should already understand React basics, JavaScript ES6+, and have completed https://tutorials.dodatech.com/frameworks/react/react-basics/ and https://tutorials.dodatech.com/frameworks/react/react-hooks/.

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 build

JSX 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 object

Component 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

HookPurposeReturns
useState(init)Local component state[value, setter]
useEffect(fn, deps)Side effects (API, timers, listeners)
useContext(ctx)Read context valuecontext 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 valuecomputed value
useCallback(fn, deps)Stable function referencememoized 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

FeatureuseMemouseCallback
ReturnsA cached valueA cached function
SyntaxuseMemo(() => expr, deps)useCallback(fn, deps)
EquivalentuseMemo(() => fn, deps)
Use caseExpensive computationsStable 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 spread

3. 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-render

Use 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

  1. What is the difference between useEffect and useLayoutEffect?

    useEffect runs asynchronously after paint. useLayoutEffect runs synchronously before paint. Use useLayoutEffect only for reading layout or preventing visual flicker.

  2. What does useId() return?

    A unique string stable across renders and SSR. Useful for accessible id attributes on form inputs and ARIA labels.

  3. What is useTransition used for?

    It marks a state update as low priority, letting React interrupt it for urgent updates (like typing) to keep the UI responsive.

  4. How does React.memo differ from useMemo?

    React.memo memoizes a component’s rendered output (skips re-render). useMemo memoizes a function’s return value (skips recomputation).

  5. What is the correct React 18 render method?

    createRoot(document.getElementById("root")).render(<App />) from react-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

What is the difference between useMemo and useCallback?
useMemo caches a computed value. useCallback caches a function reference. useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
When should I use useLayoutEffect?
When you need to read DOM layout or make visual changes before the browser paints. Overusing it blocks painting and hurts performance.
What is startTransition?
A function that wraps a state update as low priority. React can interrupt it for urgent events. Available in React 18+.
What is useDeferredValue?
Returns a deferred version of a value that may “lag behind” the real value. Useful for deferring re-rendering of expensive components while typing.
Why did React replace ReactDOM.render with createRoot?
createRoot enables React 18’s concurrent features (automatic batching, transitions, Suspense improvements). ReactDOM.render is legacy and will be removed.
What is StrictMode?
A development-only wrapper that double-invokes effects and renders to detect bugs. Does not affect production builds.

Try It Yourself

Explore the major hooks and APIs in this interactive React sandbox:

▶ Try It Yourself Edit the code and click Run

What’s Next

LessonDescription
Next.js Full-Stack ReactServer rendering, file-based routing, API routes
React Native Mobile AppsBuild iOS and Android apps with React
TypeScript for ReactType-safe hooks, components, and patterns
Node.js Backend for ReactExpress.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