Chapter 04 · HTML, CSS, JS, React, Node
React.js Frontend Framework
8 topics · 1 sections · beginner-friendly study notes · Updated
React builds UIs from reusable components that render JSX based on props and state.
The virtual DOM keeps updates efficient, hooks add state and side effects to function components, context shares global data, memoisation tunes performance, custom hooks reuse logic and React Router handles client-side navigation.
React is the most requested front-end library; hooks, keys, re-render behaviour and routing are interview staples.
Single-page apps, dashboards, design systems, and Next.
js applications.
Virtual DOM & JSX
JSX is a syntax extension that compiles to `React.createElement / jsx()` calls producing plain objects (React elements) that describe the UI. The virtual DOM is this in-memory tree; on every state change React renders a new tree, diffs it against the previous one (reconciliation) and applies only the minimal real DOM changes.
In short: You describe what the screen should look like; React works out the smallest set of changes to make it so.
Think about it
Understanding render and reconcile is the key to avoiding bugs and performance problems. An architect redrawing the blueprint and sending builders only the differences between the old and new plan.
UI = f(state).
The diffing algorithm is O(n) based on two heuristics: elements of different types produce different trees (remount), and key props identify stable children in lists.
JSX rules: a single root (or fragment `<>...
</>), className and htmlFor, camelCase attributes and events, self-closing tags, expressions in {} (not statements), and style as an object (style={{ color: "red" }}`).
Components must start with a capital letter.
Rendering must be pure: no mutation or side effects while rendering.
JSX escapes embedded strings by default, which helps prevent XSS (dangerouslySetInnerHTML bypasses it).
The virtual DOM is not inherently faster than hand-tuned DOM code; its value is declarative simplicity with good-enough performance.
Fibre architecture enables time-slicing and concurrent rendering.
Key points
Example
CodeJSX and what it compiles to:
// JSX
const el = <h1 className="title">Hello, {user.name}!</h1>;
// compiles to roughly:
const el2 = React.createElement("h1", { className: "title" }, "Hello, ", user.name, "!");
// => { type: "h1", props: { className: "title", children: [...] } }
function Banner({ items, error }) {
return (
<>
{error && <p role="alert">{error}</p>}
<ul style={{ margin: 0 }}>
{items.map(i => <li key={i.id}>{i.label}</li>)}
</ul>
</>
);
}React Components & Props
A React component is a function that takes a props object and returns JSX. Props are read-only inputs passed from parent to child using attribute syntax; special prop children carries nested content. Data flows one way: down via props, and up through callback props.
In short: Components are reusable UI functions; props are the arguments you give them.
Think about it
Components and props are the base of every React interview and codebase.
Never mutate props.
Destructure in the parameter list and give defaults ({ size = "md" }).
Composition beats inheritance: build complex UIs by nesting components and passing children or render props.
Keep components small and focused; split when a piece has its own state or reuse.
Conditional rendering uses &&, ternaries or early returns (beware 0 && <X/> rendering 0).
Pass functions as props for child-to-parent communication (onSelect).
Prop drilling (passing through many layers) is solved with composition, Context or a state library.
Validate with TypeScript or PropTypes.
Every component re-renders when its parent does unless memoised.
Never define components inside other components - they get a new identity each render and remount, losing state.
Key points
- children: Prop containing the elements nested between a component tags.
- Composition: Building UIs by combining components rather than inheriting.
- Prop drilling: Passing props through intermediate components that do not use them.
- Callback prop: Function passed down so a child can notify its parent.
Example
CodeProps, children and composition:
function Button({ variant = "primary", onClick, children }) {
return <button className={"btn btn-" + variant} onClick={onClick}>{children}</button>;
}
function Card({ title, footer, children }) {
return (
<section className="card">
<h3>{title}</h3>
<div>{children}</div>
{footer && <footer>{footer}</footer>}
</section>
);
}
function App() {
return (
<Card title="Welcome" footer={<small>v1.0</small>}>
<p>Composition lets you nest anything.</p>
<Button onClick={() => alert("Hi")}>Say hi</Button>
</Card>
);
}useState Hook & State Updates
`const [value, setValue] = useState(initial)` gives a component persistent state. Calling the setter schedules a re-render with the new value. State is a snapshot per render: the value does not change inside the current render after calling the setter.
In short: useState remembers a value between renders; changing it re-draws the component.
Think about it
State bugs (stale values, mutation, batching) are the most common beginner errors in React.
Never mutate state; create new arrays/objects (`setItems([...
items, x]), setUser({ ...
user, name })`).
Updates are batched (React 18 batches everywhere), so three setCount(count + 1) calls produce +1; use the functional form setCount(c => c + 1) when the next value depends on the previous.
Lazy initial state useState(() => expensive()) runs the initialiser once.
Setting the same value (by `Object.
is`) bails out of a re-render.
Derived data should be computed during render, not stored in state.
Use useReducer for complex transitions.
Changing a component `key` resets its state.
Controlled inputs bind value and onChange to state.
State should live as low as possible and be lifted only to the closest common parent when siblings share it.
Key points
- Immutability: Update by creating new values rather than mutating existing ones.
- Functional update:
setX(prev => next)based on the latest queued state. - Controlled input: Form element whose value is driven by React state.
- Lifting state up: Moving state to the closest common parent so siblings can share it.
Example
CodeFunctional and immutable updates:
function Counter({ step = 1 }) {
const [count, setCount] = React.useState(0);
const addThree = () => {
setCount(c => c + step);
setCount(c => c + step);
setCount(c => c + step); // +3*step. With setCount(count+step) x3 it would be only +step
};
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(c => c + step)}>+{step}</button>
<button onClick={addThree}>+3</button>
</div>
);
}
function TodoApp() {
const [todos, setTodos] = React.useState([]);
const [text, setText] = React.useState("");
const add = e => {
e.preventDefault();
if (!text.trim()) return;
setTodos(list => [...list, { id: crypto.randomUUID(), text, done: false }]);
setText("");
};
const toggle = id => setTodos(list => list.map(t => t.id === id ? { ...t, done: !t.done } : t));
return (
<form onSubmit={add}>
<input value={text} onChange={e => setText(e.target.value)} />
<ul>{todos.map(t => <li key={t.id} onClick={() => toggle(t.id)}>{t.text}</li>)}</ul>
</form>
);
}useEffect Hook & Lifecycle
useEffect(setup, deps) runs side effects (data fetching, subscriptions, timers, manual DOM work) after React paints. The optional function returned from setup is cleanup, run before the next effect and on unmount. The dependency array controls when it re-runs: none = every render, [] = once on mount, [a, b] = when a or b change.
In short: useEffect runs code after the screen updates, and can tidy up after itself.
Think about it
Dependency arrays and cleanup are the most-tested hook topics and common bug sources (infinite loops, stale data).
Think of effects as synchronisation with external systems, not as lifecycle methods.
Every reactive value used inside (props, state, functions) must be in the dependency list - the `react-hooks/exhaustive-deps` lint rule enforces this.
Omitting values causes stale closures.
Cleanup prevents leaks and race conditions: abort fetches, clear timers, unsubscribe.
In development StrictMode mounts, unmounts and remounts to expose missing cleanup.
Rules of Hooks: only call hooks at the top level of components or custom hooks, never in loops, conditions or nested functions, because React matches hooks by call order.
Do not use effects to derive state from props (compute during render) or to respond to user events (use handlers).
useLayoutEffect runs before paint for measurements.
useRef stores mutable values without re-rendering.
Key points
- Dependency array: Values that, when changed, re-run the effect.
- Cleanup function: Function returned from an effect, run before re-run and on unmount.
- Stale closure: Callback captures old state because a dependency was omitted.
- Rules of Hooks: Call hooks only at the top level and only from React functions.
Read more
Example
CodeFetching with cleanup and a timer:
function UserCard({ id }) {
const [user, setUser] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
const controller = new AbortController();
setUser(null); setError(null);
fetch("/api/users/" + id, { signal: controller.signal })
.then(r => { if (!r.ok) throw new Error("HTTP " + r.status); return r.json(); })
.then(setUser)
.catch(e => { if (e.name !== "AbortError") setError(e); });
return () => controller.abort(); // cleanup avoids race conditions
}, [id]); // re-run when id changes
if (error) return <p>Error loading user</p>;
if (!user) return <p>Loading...</p>;
return <h3>{user.name}</h3>;
}
function Clock() {
const [now, setNow] = React.useState(() => new Date());
React.useEffect(() => {
const t = setInterval(() => setNow(new Date()), 1000);
return () => clearInterval(t);
}, []);
return <time>{now.toLocaleTimeString()}</time>;
}Context API & Global State
Context lets a component provide a value to its entire subtree without passing props through each level. Create with createContext(default), supply with <Ctx.Provider value={...}> and read with useContext(Ctx). It is commonly combined with useReducer for lightweight global state.
In short: A shared box any component below can open without props being handed down.
Think about it
Avoids prop drilling and is the built-in answer to global state in React interviews.
Every consumer re-renders whenever the provider value changes (by reference), so memoise the value (`useMemo`) and avoid creating a new object each render.
Split contexts by concern or by update frequency (state vs dispatch) to limit re-renders.
Context is great for low-frequency data such as theme, locale and the auth user; for frequently changing or large state, libraries like Redux Toolkit, Zustand or Jotai offer selectors and finer subscriptions.
Wrap the hook (useAuth) to throw a helpful error when used outside its provider.
Provider placement matters: put it as low as possible.
Context does not replace props for ordinary component communication.
Key points
- Provider: Component that supplies the context value to descendants.
- Consumer / useContext: Reads the nearest provider value for a context.
- Prop drilling: Passing data through many intermediate components.
Example
CodeTheme context with a safe hook:
const ThemeContext = React.createContext(null);
function ThemeProvider({ children }) {
const [theme, setTheme] = React.useState("light");
const toggle = React.useCallback(() => setTheme(t => (t === "light" ? "dark" : "light")), []);
const value = React.useMemo(() => ({ theme, toggle }), [theme, toggle]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
function useTheme() {
const ctx = React.useContext(ThemeContext);
if (!ctx) throw new Error("useTheme must be used inside ThemeProvider");
return ctx;
}
function ThemeButton() {
const { theme, toggle } = useTheme();
return <button onClick={toggle}>Theme: {theme}</button>;
}
// <ThemeProvider><App /></ThemeProvider>useMemo & useCallback Optimization
useMemo(() => compute(a, b), [a, b]) caches a computed value between renders; useCallback(fn, deps) caches a function identity. `React.memo(Component)` skips re-rendering a component when its props are shallowly equal.
In short: Remember results and functions so unchanged work is not repeated.
Think about it
Interviewers ask when memoisation helps and when it is wasted effort.
They are performance optimisations, never required for correctness.
Memoisation helps when (1) a calculation is genuinely expensive, (2) the value is passed to a `React.
memo` child or used as an effect dependency and must stay referentially stable.
Using them everywhere adds comparison overhead and complexity.
Without `React.
memo on the child, useCallback` on its props has no effect.
Dependencies must be complete or values go stale.
Measure first with React DevTools Profiler.
Other techniques: move state down, lift content up (children props), split components, virtualise long lists (react-window), lazy load with `React.
lazy and Suspense, and use useTransition/useDeferredValue` for responsiveness.
The React Compiler can add memoisation automatically.
Key points
Example
Codememo + useMemo + useCallback together:
const Row = React.memo(function Row({ item, onSelect }) {
console.log("render row", item.id);
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
function List({ items }) {
const [query, setQuery] = React.useState("");
const [selected, setSelected] = React.useState(null);
const visible = React.useMemo(
() => items.filter(i => i.name.toLowerCase().includes(query.toLowerCase())),
[items, query]
);
const handleSelect = React.useCallback(id => setSelected(id), []); // stable identity for Row
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<p>Selected: {selected}</p>
<ul>{visible.map(i => <Row key={i.id} item={i} onSelect={handleSelect} />)}</ul>
</>
);
}Custom React Hooks
A custom hook is a function whose name starts with use that calls other hooks to encapsulate reusable stateful logic. Each call to a custom hook has its own independent state.
In short: Pull repeated hook logic into a function you can reuse in many components.
Think about it
Shows mastery of hooks and clean architecture; a common live-coding task (useDebounce, useFetch).
Custom hooks share logic, not state: two components using useCounter() get separate counters.
They must follow the Rules of Hooks, and the use prefix lets linters check this.
Typical examples: useFetch, useLocalStorage, useDebounce, useMediaQuery, useOnClickOutside, useToggle.
Return values can be arrays (positional like useState) or objects (named).
Make them composable and testable (via renderHook).
Keep the API small, handle cleanup and race conditions inside, and accept options rather than hard-coding.
They replace older patterns such as higher-order components and render props for logic reuse.
Key points
- use prefix: Naming convention that signals a hook and enables lint rules.
- Logic reuse: Sharing behaviour between components without sharing state.
- Debounce: Delay an update until input has paused for a period.
Example
CodeuseLocalStorage, useDebounce and useFetch:
function useLocalStorage(key, initial) {
const [value, setValue] = React.useState(() => {
try { const raw = localStorage.getItem(key); return raw ? JSON.parse(raw) : initial; }
catch { return initial; }
});
React.useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]);
return [value, setValue];
}
function useDebounce(value, delay = 300) {
const [debounced, setDebounced] = React.useState(value);
React.useEffect(() => {
const t = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(t);
}, [value, delay]);
return debounced;
}
function useFetch(url) {
const [state, setState] = React.useState({ data: null, error: null, loading: true });
React.useEffect(() => {
const ctrl = new AbortController();
setState({ data: null, error: null, loading: true });
fetch(url, { signal: ctrl.signal })
.then(r => { if (!r.ok) throw new Error("HTTP " + r.status); return r.json(); })
.then(data => setState({ data, error: null, loading: false }))
.catch(error => { if (error.name !== "AbortError") setState({ data: null, error, loading: false }); });
return () => ctrl.abort();
}, [url]);
return state;
}
function Search() {
const [q, setQ] = useLocalStorage("q", "");
const debounced = useDebounce(q, 400);
const { data, loading } = useFetch("/api/search?q=" + encodeURIComponent(debounced));
return <><input value={q} onChange={e => setQ(e.target.value)} />{loading ? "..." : data?.length}</>;
}React Router Architecture
React Router is the standard client-side routing library. It maps URLs to components without full page reloads using the History API. Core pieces: createBrowserRouter/BrowserRouter, route objects or <Route> elements, <Link>/<NavLink>, <Outlet> for nested layouts, and hooks useParams, useNavigate, useSearchParams, useLocation.
In short: Change the URL and swap the visible component without reloading the page.
Think about it
Every real React app has multiple pages; routing, layouts and protected routes are common interview topics.
Nested routes mirror UI hierarchy: a parent route renders a layout with an <Outlet /> where the matching child appears.
Dynamic segments (/users/:id) are read with useParams.
An index route renders at the parent path; * is the catch-all 404.
Use <Link to> instead of <a href> to avoid a full reload.
Data routers add loader (fetch before render), action (handle form submissions) and errorElement, giving route-level loading and error handling.
Protect pages with a wrapper that redirects unauthenticated users via <Navigate>.
Code split routes with `React.
lazy`.
The server must fall back to `index.
html` for unknown paths so deep links work on refresh.
Frameworks such as Next.
js provide file-based routing and server rendering on top of similar ideas.
Key points
- SPA: Single-page application: one HTML page with client-side navigation.
- Outlet: Placeholder where a nested child route renders.
- Loader: Route function that fetches data before the component renders.
- History API: Browser API (pushState) that changes the URL without reloading.
Example
CodeNested routes, params and a protected route:
import { createBrowserRouter, RouterProvider, Link, NavLink, Outlet, useParams, Navigate, useNavigate } from "react-router-dom";
function Layout() {
return (
<>
<nav>
<NavLink to="/">Home</NavLink> <NavLink to="/users">Users</NavLink>
</nav>
<main><Outlet /></main>
</>
);
}
function UserPage() {
const { id } = useParams();
return <h2>User #{id}</h2>;
}
function RequireAuth({ user, children }) {
return user ? children : <Navigate to="/login" replace />;
}
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{ index: true, element: <h1>Home</h1> },
{ path: "users", element: <ul><li><Link to="/users/1">Asha</Link></li></ul> },
{ path: "users/:id", element: <RequireAuth user={currentUser}><UserPage /></RequireAuth> },
{ path: "*", element: <h1>404 - Not found</h1> },
],
},
]);
// <RouterProvider router={router} />Solved examples
Why does this fail to update the UI? const [n, setN] = useState(0); <button onClick={() => { n = n + 1; }}>
Reason and fix
Formula Applied:—Approach note: Never mutate state directly.
A component calls setCount(count + 1) three times in one click handler. What is the final increment? How to get +3?
Final value and fix
Formula Applied:—Approach note: Use the updater function when the new state depends on the old state.
An effect uses a "query" prop but has an empty dependency array. What bug occurs and how to fix it?
Bug and fix
Formula Applied:—Approach note: Include every reactive value used inside the effect; the lint rule react-hooks/exhaustive-deps helps.
Every component under <ThemeContext.Provider value={{ theme, toggle }}> re-renders on every parent render. Why and how to fix it?
Cause and fix
Formula Applied:—Approach note: Stable provider values prevent needless consumer renders.
Write a useToggle custom hook returning [on, toggle].
Hook code
Formula Applied:—Approach note: Custom hooks share logic, not state - each caller gets its own.
Design routes: a layout with nav, a /courses list, a /courses/:id detail page and a 404 page.
Route configuration
Formula Applied:—Approach note: Nested routes mirror the UI hierarchy via Outlet.
Real-world applications
Using React.js Frontend Framework in real projects
Single-page apps, dashboards, design systems, and Next.js applications.
Common mistakes
❌ Myth: Using the array index as key is always fine.
Why this is wrong: On reorder/insert/delete, state and DOM nodes mismatch items.
✅ Verified Truth: Use a stable unique id; index only for static lists.
⚠️ Exam Tip: Explain with an input-in-list example.
❌ Myth: setState updates the value immediately.
Why this is wrong: Updates are batched and applied on the next render.
✅ Verified Truth: Use the updater form or effects to act on the new value.
⚠️ Exam Tip: State is a snapshot per render.
❌ Myth: useEffect with [] means "componentDidMount" exactly.
Why this is wrong: It also needs cleanup semantics and runs twice in StrictMode dev.
✅ Verified Truth: Treat effects as synchronisation with external systems, not lifecycle hooks.
⚠️ Exam Tip: Mention cleanup.
❌ Myth: The virtual DOM is always faster than the real DOM.
Why this is wrong: It adds work; its benefit is declarative code with good-enough updates.
✅ Verified Truth: Performance comes from minimal DOM changes plus sensible component design.
⚠️ Exam Tip: Say "predictable and declarative", not "faster".
❌ Myth: Wrap everything in useMemo and useCallback for speed.
Why this is wrong: Memoisation has its own cost and often has no effect without memoised children.
✅ Verified Truth: Profile first; memoise expensive work or stabilise props of memoised children.
⚠️ Exam Tip: Explain when they matter.
❌ Myth: Context is a replacement for all state management.
Why this is wrong: Any value change re-renders all consumers and there are no selectors.
✅ Verified Truth: Use Context for low-frequency data; use a store library for high-frequency, large state.
⚠️ Exam Tip: Mention theme/auth as ideal uses.
Revision notes
React builds UIs from reusable components that render JSX based on props and state. The virtual DOM keeps updates efficient, hooks add state and side effects to function components, context shares global data, memoisation tunes performance, custom hooks reuse logic and React Router handles client-side navigation.
High-Yield Quick Revision Points
- UI = f(state); JSX compiles to createElement; virtual DOM diff = reconciliation
- props read-only, flow down; callbacks flow up; children for composition
- never mutate state; setX(prev => ...) for dependent updates; state is a snapshot
- useEffect deps [] / [a] / none; cleanup on re-run and unmount
- rules of hooks: top level only
- stable keys for lists
- Context: memoise provider value; good for theme/auth, not high-frequency state
- useMemo/useCallback/React.memo: only when measured or needed for stable identity
- custom hooks share logic not state; name starts with use
- React Router: nested routes + Outlet, useParams, protected routes, server fallback to index.html
Practice questions
Which flows from parent to child in React?
useEffect(fn, []) runs:
Why must hooks not be called inside conditions?
Best key for items from a database list is:
What does React do with the virtual DOM after state changes?
Which hook reads the nearest context value?
useCallback(fn, deps) returns:
A custom hook name must start with:
In React Router, where does a nested child route render?
Which is true about props?