Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

React Documentation

The most popular library for building user interfaces from components — props, state, hooks and routing.

React is a JavaScript library for building user interfaces from small, reusable components. You describe what the UI should look like for a given state, and React updates the page efficiently when that state changes. It is the most popular front-end library and the "R" in the MERN stack.

1. Introduction & Setup

Install Node.js (LTS), then create a project with Vite:

npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev        # opens http://localhost:5173
npm run build      # production build in dist/

src/main.jsx mounts the app into <div id="root"> in index.html:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);
// src/App.jsx
export default function App() {
  return <h1>Hello, Codify!</h1>;
}

Output:

Hello, Codify!        (rendered as a big heading in the browser)

Install the React Developer Tools browser extension to inspect components and state.

⚠️ Common error: a blank page — open the browser console. Usually it's an import path typo or a component that doesn't export default.

2. JSX & Basic Syntax

JSX looks like HTML inside JavaScript. Rules:

  • Return one parent element (or a fragment <>...</>).
  • Use className instead of class, htmlFor instead of for.
  • Close every tag: <img />, <br />.
  • Put JavaScript expressions in { }.
  • Inline styles are objects: style={{ color: "red", fontSize: 18 }}.
export default function Profile() {
  const user = { name: "Asha", skills: ["React", "Node"], online: true };
  return (
    <>
      <h2 className="title">{user.name.toUpperCase()}</h2>
      <p style={{ color: user.online ? "green" : "gray" }}>
        {user.online ? "Online" : "Offline"} · {user.skills.length} skills
      </p>
      <label htmlFor="msg">Message</label>
      <input id="msg" placeholder={`Say hi to ${user.name}`} />
    </>
  );
}

Output:

ASHA
Online · 2 skills          (green text)
Message [Say hi to Asha   ]

⚠️ Common error: Adjacent JSX elements must be wrapped in an enclosing tag — wrap them in <>...</> or a <div>.

3. Components & Props

A component is a function that returns JSX. Names start with a capital letter. Props pass data from parent to child (read-only).

function Avatar({ name, size = 40 }) {          // destructure props, default value
  return (
    <span className="avatar" style={{ width: size, height: size }}>
      {name[0]}
    </span>
  );
}

function UserCard({ user, children }) {         // children = content between the tags
  return (
    <div className="card">
      <Avatar name={user.name} size={56} />
      <h3>{user.name}</h3>
      {children}
    </div>
  );
}

export default function App() {
  return (
    <UserCard user={{ name: "Ravi" }}>
      <p>Learning React on Codify</p>
    </UserCard>
  );
}

Output:

[R]  Ravi
     Learning React on Codify

⚠️ Common error: a lowercase component name (<userCard />) is treated as an unknown HTML tag and renders nothing useful.

4. State with useState

State is data that changes over time. Updating state re-renders the component.

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>+1</button>
      <button onClick={() => setCount((c) => c + 5)}>+5</button>   {/* functional update */}
      <button onClick={() => setCount(0)} disabled={count === 0}>Reset</button>
    </div>
  );
}

Output:

Clicked 0 times  [+1] [+5] [Reset (disabled)]
→ click +1, +5 →  Clicked 6 times

Objects and arrays must be updated immutably — create a new copy:

const [user, setUser] = useState({ name: "Asha", age: 20 });
setUser({ ...user, age: 21 });                       // ✅ new object

const [todos, setTodos] = useState([]);
setTodos([...todos, { id: Date.now(), text: "Learn hooks" }]);    // add
setTodos(todos.filter((t) => t.id !== id));                       // remove
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));  // update

⚠️ Common error: user.age = 21; setUser(user) — mutating state directly doesn't re-render because the object reference didn't change.

5. Conditional Rendering

function Status({ loading, error, items }) {
  if (loading) return <p>Loading…</p>;                    // early return
  if (error) return <p className="error">{error}</p>;

  return (
    <div>
      {items.length === 0 && <p>No items yet.</p>}         {/* && */}
      <p>{items.length > 5 ? "Many items" : "A few items"}</p>   {/* ternary */}
    </div>
  );
}

export default function App() {
  return <Status loading={false} error="" items={[1, 2]} />;
}

Output:

A few items

⚠️ Common error: {count && <Badge />} renders a literal 0 when count is 0. Use {count > 0 && <Badge />}.

6. Lists & Keys

const courses = [
  { id: 1, title: "DSA in C++", lessons: 120 },
  { id: 2, title: "React Basics", lessons: 40 },
  { id: 3, title: "Node.js API", lessons: 32 },
];

export default function CourseList() {
  return (
    <ul>
      {courses
        .filter((c) => c.lessons < 100)
        .map((c) => (
          <li key={c.id}>
            {c.title} — {c.lessons} lessons
          </li>
        ))}
    </ul>
  );
}

Output:

• React Basics — 40 lessons
• Node.js API — 32 lessons

⚠️ Common error: Each child in a list should have a unique "key" prop. Use a stable id — not the array index if items can be reordered or deleted.

7. Events & Forms

Events use camelCase (onClick, onChange, onSubmit). Controlled inputs keep their value in state.

import { useState } from "react";

export default function SignupForm() {
  const [form, setForm] = useState({ email: "", plan: "free", agree: false });
  const [message, setMessage] = useState("");

  const update = (e) => {
    const { name, value, type, checked } = e.target;
    setForm({ ...form, [name]: type === "checkbox" ? checked : value });
  };

  const submit = (e) => {
    e.preventDefault();                                   // stop the page reload
    if (!form.email.includes("@")) return setMessage("Enter a valid email");
    setMessage(`Signed up ${form.email} on the ${form.plan} plan`);
  };

  return (
    <form onSubmit={submit}>
      <input name="email" value={form.email} onChange={update} placeholder="Email" />
      <select name="plan" value={form.plan} onChange={update}>
        <option value="free">Free</option>
        <option value="pro">Pro</option>
      </select>
      <label>
        <input type="checkbox" name="agree" checked={form.agree} onChange={update} /> I agree
      </label>
      <button disabled={!form.agree}>Sign up</button>
      {message && <p>{message}</p>}
    </form>
  );
}

Output:

[Email        ] [Free ▼] [ ] I agree [Sign up (disabled)]
→ type asha@example.com, choose Pro, tick I agree, click Sign up →
Signed up asha@example.com on the pro plan

⚠️ Common error: onClick={handleClick()} calls the function during render. Pass the function: onClick={handleClick} or onClick={() => handleClick(id)}.

8. Hooks: useEffect, useRef, useMemo & more

useEffect runs side effects (data fetching, timers, subscriptions) after render.

import { useEffect, useRef, useState } from "react";

export default function Timer() {
  const [seconds, setSeconds] = useState(0);
  const [running, setRunning] = useState(true);
  const inputRef = useRef(null);                       // DOM reference (no re-render)

  useEffect(() => {
    if (!running) return;
    const id = setInterval(() => setSeconds((s) => s + 1), 1000);
    return () => clearInterval(id);                    // cleanup when stopped/unmounted
  }, [running]);                                       // re-run only when `running` changes

  useEffect(() => {
    document.title = `${seconds}s elapsed`;
  }, [seconds]);

  return (
    <div>
      <p>{seconds}s</p>
      <button onClick={() => setRunning(!running)}>{running ? "Pause" : "Resume"}</button>
      <input ref={inputRef} placeholder="Notes" />
      <button onClick={() => inputRef.current.focus()}>Focus notes</button>
    </div>
  );
}

Output:

0s → 1s → 2s …  (tab title updates too)  [Pause]
[Notes      ] [Focus notes]
Hook Use
useState local state
useEffect side effects after render
useRef DOM access or a mutable value that doesn't re-render
useMemo cache an expensive calculation
useCallback cache a function (for memoised children)
useContext read shared data without prop drilling
useReducer complex state with actions

Custom hooks reuse stateful logic:

function useLocalStorage(key, initial) {
  const [value, setValue] = useState(() => JSON.parse(localStorage.getItem(key)) ?? initial);
  useEffect(() => localStorage.setItem(key, JSON.stringify(value)), [key, value]);
  return [value, setValue];
}
// const [theme, setTheme] = useLocalStorage("theme", "dark");

⚠️ Common error: an infinite loop — useEffect(() => setData(...)) with no dependency array runs after every render. Add the correct dependencies. Also: hooks must be called at the top level, never inside ifs or loops.

9. Routing (React Router)

npm install react-router-dom
import { BrowserRouter, Routes, Route, Link, NavLink, useParams, useNavigate } from "react-router-dom";

function Home() {
  return <h1>Home</h1>;
}

function CourseDetail() {
  const { id } = useParams();                    // /courses/42 → id = "42"
  const navigate = useNavigate();
  return (
    <>
      <h1>Course {id}</h1>
      <button onClick={() => navigate("/")}>Back home</button>
    </>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <nav>
        <NavLink to="/">Home</NavLink> | <Link to="/courses/42">Course 42</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/courses/:id" element={<CourseDetail />} />
        <Route path="*" element={<h1>404 — Not found</h1>} />
      </Routes>
    </BrowserRouter>
  );
}

Output:

Home | Course 42
Home                       (at /)
Course 42 [Back home]      (after clicking "Course 42" → URL /courses/42, no page reload)

⚠️ Common error: refreshing /courses/42 on a deployed site gives 404 — configure the host to serve index.html for all routes (e.g. a rewrite in vercel.json or _redirects on Netlify).

10. API Integration & Advanced Concepts

Fetching data with loading and error states:

import { useEffect, useState } from "react";

export default function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();
    fetch("https://jsonplaceholder.typicode.com/users", { signal: controller.signal })
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then(setUsers)
      .catch((err) => err.name !== "AbortError" && setError(err.message))
      .finally(() => setLoading(false));
    return () => controller.abort();             // cancel if the component unmounts
  }, []);

  if (loading) return <p>Loading…</p>;
  if (error) return <p>Error: {error}</p>;
  return (
    <ul>
      {users.slice(0, 3).map((u) => (
        <li key={u.id}>{u.name}</li>
      ))}
    </ul>
  );
}

Output:

Loading…
→ then:
• Leanne Graham
• Ervin Howell
• Clementine Bauch

Sending data (POST) — for example with axios:

import axios from "axios";
const api = axios.create({ baseURL: import.meta.env.VITE_API_URL });
const { data } = await api.post("/todos", { text: "Learn React" });

Context shares data (theme, logged-in user) without passing props through every level:

import { createContext, useContext, useState } from "react";

const ThemeContext = createContext("light");

function ThemeButton() {
  const { theme, toggle } = useContext(ThemeContext);
  return <button onClick={toggle}>Theme: {theme}</button>;
}

export default function App() {
  const [theme, setTheme] = useState("light");
  const toggle = () => setTheme((t) => (t === "light" ? "dark" : "light"));
  return (
    <ThemeContext.Provider value={{ theme, toggle }}>
      <ThemeButton />
    </ThemeContext.Provider>
  );
}

Output:

[Theme: light]  → click →  [Theme: dark]

useReducer for complex state:

import { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "add": return { ...state, items: [...state.items, action.item] };
    case "clear": return { ...state, items: [] };
    default: return state;
  }
}

export default function Cart() {
  const [state, dispatch] = useReducer(reducer, { items: [] });
  return (
    <>
      <p>{state.items.length} items</p>
      <button onClick={() => dispatch({ type: "add", item: "Book" })}>Add book</button>
      <button onClick={() => dispatch({ type: "clear" })}>Clear</button>
    </>
  );
}

Performance tools: React.memo, useMemo, useCallback, code-splitting with lazy() + <Suspense>. Also explore: React Query/TanStack Query for server data, Zustand/Redux Toolkit for global state, Next.js for server rendering, and testing with Vitest + React Testing Library.

11. Examples with Output

Example 1 — To-do list

import { useState } from "react";

export default function Todos() {
  const [text, setText] = useState("");
  const [todos, setTodos] = useState([]);

  const add = (e) => {
    e.preventDefault();
    if (!text.trim()) return;
    setTodos([...todos, { id: crypto.randomUUID(), text, done: false }]);
    setText("");
  };
  const toggle = (id) => setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
  const remove = (id) => setTodos(todos.filter((t) => t.id !== id));

  return (
    <form onSubmit={add}>
      <input value={text} onChange={(e) => setText(e.target.value)} placeholder="New task" />
      <button>Add</button>
      <ul>
        {todos.map((t) => (
          <li key={t.id}>
            <label style={{ textDecoration: t.done ? "line-through" : "none" }}>
              <input type="checkbox" checked={t.done} onChange={() => toggle(t.id)} /> {t.text}
            </label>
            <button type="button" onClick={() => remove(t.id)}>✕</button>
          </li>
        ))}
      </ul>
      <p>{todos.filter((t) => !t.done).length} left</p>
    </form>
  );
}
[New task      ] [Add]
[✓] L̶e̶a̶r̶n̶ ̶J̶S̶X̶  ✕
[ ] Learn hooks  ✕
1 left

Example 2 — Search with debounce (custom hook)

import { useEffect, useState } from "react";

function useDebounce(value, delay = 300) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return debounced;
}

const LANGS = ["Python", "Java", "JavaScript", "TypeScript", "Go", "Rust"];

export default function Search() {
  const [q, setQ] = useState("");
  const query = useDebounce(q);
  const results = LANGS.filter((l) => l.toLowerCase().includes(query.toLowerCase()));
  return (
    <>
      <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search languages" />
      <p>{results.join(", ")}</p>
    </>
  );
}
[script     ]
JavaScript, TypeScript        (updates 300 ms after you stop typing)

12. Practice Problems

  1. Counter app with increment, decrement, reset and a step size input.
  2. To-do app with add, edit, delete, filter (all/active/done) and localStorage persistence.
  3. Fetch and display GitHub users with a search box, loading spinner and error message.
  4. Multi-step form (3 steps) with validation and a summary page.
  5. Light/dark theme toggle using Context.
  6. Product listing with cart (useReducer): add, remove, quantity, total price.
  7. Build a small blog with React Router: list page, detail page /posts/:id, and a 404 page.
  8. Connect a React front-end to your own Node/Express API (see the Node.js docs).

13. Interview Questions

1. What is the virtual DOM? A lightweight JS representation of the UI. On state change React builds a new tree, diffs it with the previous one (reconciliation) and applies only the needed DOM updates.

2. Props vs state? Props are inputs passed from the parent (read-only); state is data owned and updated by the component itself.

3. Why are keys needed in lists? They let React identify which items changed, were added or removed, so it can reuse DOM nodes and keep component state correct.

4. What does useEffect do and what is the dependency array? Runs side effects after render. The dependency array controls when it re-runs: [] once after mount, [a, b] when a or b change, none = after every render. The returned function is the cleanup.

5. Controlled vs uncontrolled components? Controlled inputs get their value from React state (value + onChange); uncontrolled ones keep their own DOM state, read with a ref.

6. What are the rules of hooks? Call hooks only at the top level of React functions (not in loops/conditions/nested functions) and only from components or custom hooks.

7. What is prop drilling and how do you avoid it? Passing props through many layers that don't use them. Avoid with Context, composition (children), or a state library.

8. useMemo vs useCallback? useMemo caches a computed value; useCallback caches a function reference. Both recompute only when dependencies change.

9. What is lifting state up? Moving shared state to the closest common parent so sibling components can use and update it via props.

10. Why does React StrictMode run effects twice in development? To surface bugs from missing cleanups and impure renders. It doesn't happen in production builds.

14. Cheat Sheet & References

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"));

Official documentation