Core Definitions & Key Concepts
Core Definitions & Key Concepts
What is React.js and what is its core philosophy
React is an open-source JavaScript front-end library developed by Facebook for building user interfaces based on composable components, declarative state-driven rendering, and a Virtual DOM.
What is JSX (JavaScript XML)
A syntax extension for JavaScript that allows developers to write HTML-like markup directly within JavaScript code, which transpilers (Babel) convert into standard React.createElement() function calls.
The Virtual DOM and the Reconciliation algorithm
A lightweight in-memory representation of the real DOM. When component state changes, React creates a new Virtual DOM tree, diffs it against the previous tree using the Reconciliation algorithm (Fiber), and batches minimal necessary updates to the real browser DOM.
Props and State in React
- Props (Properties): Immutable, read-only data passed downward from a parent component to a child component.
- State: Mutable, locally managed data owned by the component that determines its dynamic behavior and triggers re-rendering upon modification.
What are React Hooks
Functions introduced in React 16.8 that allow functional components to use state and other React lifecycle features without writing ES6 class components (e.g., useState, useEffect, useContext).
The useEffect Hook and its dependency array
Handles side-effects (data fetching, DOM subscriptions, timers) in functional components.
- No array: Runs after every render.
- Empty array `[]`: Runs once after initial mount.
- Array with variables `[a, b]`: Runs when
aorbvalues change. Return function acts as cleanup on unmount.
What is an Error Boundary in React
A React class component that implements static getDerivedStateFromError() or componentDidCatch() to catch JavaScript errors anywhere in its child component tree, log errors, and display a fallback UI instead of crashing the entire page.
What is Redux and what are its three fundamental principles
A predictable global state management container for JavaScript apps.
- Single source of truth (One global Store)
- State is read-only (Mutations only via Actions)
- Changes are made with pure functions (Reducers)
What is Redux Saga
A middleware library that aims to make application side-effects (asynchronous operations like data fetching) easier to manage, test, and execute, leveraging ES6 generator functions (function*, yield).
What is Server-Side Rendering (SSR) and how does it benefit web applications
Rendering React components into static HTML strings on the server before transmitting them to the browser (e.g., Next.js). Benefits: Ultra-fast First Contentful Paint (FCP) and superior Search Engine Optimization (SEO).
Conceptual & Architectural Analysis
Conceptual & Architectural Analysis
Compare Class Components vs Functional Components with React Hooks
| Dimension | Class Components | Functional Components (with Hooks) |
|---|---|---|
| Syntax | ES6 Class extending React.Component | Pure JavaScript functions |
| State Handling | this.state and this.setState() | useState() and useReducer() Hooks |
| Lifecycle Methods | componentDidMount, componentDidUpdate | Unified useEffect() Hook with dependencies |
| `this` Keyword | Requires manual method binding in constructor | No this keyword; lexical scope |
| Code Reusability | Higher-Order Components (HOC), Render Props | Custom Hooks (clean, composable) |
| Industry Standard | Legacy maintenance | Modern standard (React 18+) |
Detail the React Component Lifecycle in Modern Functional Architecture
Lifecycle Mapping via Hooks
Mounting: Functional Component Execution -> DOM Updated -> useEffect([]) runs
Updating: Props/State Change -> Re-render -> Cleanup (if dep changed) -> useEffect([deps])
Unmounting: Component Removed from DOM -> useEffect cleanup return () => {}- Mounting:
useEffect(() => { init(); return () => cleanup(); }, [])mimicscomponentDidMountandcomponentWillUnmount. - Updating:
useEffect(() => { ... }, [props.id])mimicscomponentDidUpdate. - Memoization:
useMemocaches expensive calculations;useCallbackcaches function definitions across renders.
React Context API vs Redux for State Management
State Architecture Comparison
- Context API: Built directly into React (
createContext,useContext). Excellent for low-frequency global state (theme switching, authenticated user profile, localization). Triggers re-renders on all consuming child components whenever context value updates. - Redux / Redux Toolkit (RTK): External architectural framework. Excellent for complex enterprise state with frequent updates, fine-grained selector subscriptions (
useSelector), robust time-travel debugging (Redux DevTools), and centralized middleware pipelines.
Webpack and Modern Build Tooling (Vite, Rollup, Babel)
Front-End Tooling Evolution
- Webpack: Traditional static module bundler. Analyzes import graphs and recursively bundles modules, CSS, and assets into production bundles using loaders and plugins. Slower cold start due to full bundle compilation.
- Vite: Next-generation frontend tooling. Leverages native browser ES Modules (ESM) during development for instantaneous server start (< 300\,ms) and Hot Module Replacement (HMR). Uses Rollup for optimized production builds.
- Babel: JavaScript compiler converting modern ESNext and JSX syntax into backwards-compatible ES5 code.
Detail Client-Side Routing: React Router Architecture
React Router Mechanics
- Intercepts browser URL changes using the HTML5 History API (
pushState,replaceState) without triggering full browser page reloads. - Core Components:
<BrowserRouter>,<Routes>,<Route path="..." element={<Component />} />, and<Outlet />for nested layout routing. - Hooks:
useNavigate()for programmatic redirects,useParams()to extract URL route parameters (e.g.,:courseId), anduseLocation()for current URL inspection.
In-Depth Analysis & Implementation
In-Depth Analysis & Implementation
Provide an In-Depth Architectural Dissection of the React Fiber Reconciliation Algorithm and Virtual DOM Diffing Heuristics
React Fiber Reconciliation Engine
+-----------------------------------------------------------------------------------------+
| REACT FIBER RECONCILIATION ARCHITECTURE |
| |
| Phase 1: Render / Reconciliation (Interruptible Work) |
| - Traverses Fiber Tree (Child, Sibling, Return pointers) |
| - Breaks rendering into time-sliced units of work (requestIdleCallback) |
| - Prioritizes high-priority user interactions (typing) over low-priority (data load) |
| | |
| v (Produces Effect List) |
| Phase 2: Commit Phase (Synchronous & Non-Interruptible) |
| - Applies DOM mutations to real browser DOM |
| - Executes useLayoutEffect and useEffect hooks |
+-----------------------------------------------------------------------------------------+1. The O(N) Heuristic Diffing Rules
A complete tree diffing algorithm has O(N^3) computational complexity. React achieves linear O(N) complexity based on two practical assumptions:
- Different Element Types: Two elements of different HTML/component types produce radically different trees. Changing
<div>to<span>completely destroys the subtree and mounts anew. - Keys on Child Lists: Developers provide stable, unique
keyprops on list items. Allows React to identify which items were inserted, deleted, or reordered without tearing down existing DOM nodes.
2. The Fiber Node Data Structure
Each Fiber is a JavaScript object representing a unit of work:
FiberNode = {
tag: WorkTag, // FunctionComponent, ClassComponent, HostComponent
key: null | string, // Reconciliation unique key
stateNode: any, // Instance of class component or real DOM element
child: Fiber | null, // Pointer to first direct child
sibling: Fiber | null, // Pointer to next sibling
return: Fiber | null, // Pointer to parent node
alternate: Fiber | null// Pointer to work-in-progress fiber on double-buffering pool
};Design and Build a Complete Enterprise Global State Architecture with Redux Toolkit (RTK) and Redux Thunk
Redux Toolkit (RTK) Enterprise Implementation
1import { configureStore, createAsyncThunk, createSlice } from '@reduxjs/toolkit';2
3// 1. Asynchronous Thunk Action4export const fetchCourses = createAsyncThunk(5 'courses/fetchCourses',6 async (semesterId, { rejectWithValue }) => {7 try {8 const response = await fetch(`/api/semesters/${semesterId}/courses`);9 if (!response.ok) throw new Error('Network error');10 return await response.json();11 } catch (err) {12 return rejectWithValue(err.message);13 }14 }15);16
17// 2. Normalized State Slice18const coursesSlice = createSlice({19 name: 'courses',20 initialState: { items: [], status: 'idle', error: null },21 reducers: {22 clearCourses: (state) => { state.items = []; }23 },24 extraReducers: (builder) => {25 builder26 .addCase(fetchCourses.pending, (state) => { state.status = 'loading'; })27 .addCase(fetchCourses.fulfilled, (state, action) => {28 state.status = 'succeeded';29 state.items = action.payload;30 })31 .addCase(fetchCourses.rejected, (state, action) => {32 state.status = 'failed';33 state.error = action.payload;34 });35 }36});37
38export const store = configureStore({39 reducer: { courses: coursesSlice.reducer }40});Analyze Server-Side Rendering (SSR) vs Static Site Generation (SSG) vs Client-Side Rendering (CSR)
Rendering Paradigm Architecture Matrix
| Paradigm | Where HTML is Built | TTFB (Time to First Byte) | FCP (First Contentful Paint) | SEO Friendliness | Server Compute Load |
|---|---|---|---|---|---|
| CSR (Client-Side) | Client Browser | Instantaneous (Static CDN) | Slow (Must download & run JS) | Poor without prerendering | Zero (Static hosting) |
| SSR (Server-Side) | On-Demand per Request | Slower (Server execution) | Fast (Full HTML rendered) | Excellent | High (Scales with traffic) |
| SSG (Static Gen) | At Build Time (Ahead) | Ultra-Fast (Edge CDN cache) | Ultra-Fast (Pre-rendered) | Excellent | Zero at runtime |
| ISR (Incremental) | Background revalidation | Ultra-Fast | Ultra-Fast | Excellent | Low (Revalidates on interval) |
Architectural Synthesis:
Modern enterprise architectures (Next.js) deploy hybrid rendering: SSG/ISR for static marketing pages and course catalogs; SSR for dynamic authenticated student dashboards; and CSR for interactive quiz test interfaces.
Important Exam Points & Quick Revision
Important Exam Points & Quick Revision
Examiners frequently evaluate: Props vs State (2/5 marks), Virtual DOM and Reconciliation algorithm (10/15 marks), Redux 3 principles (5 marks), and Class vs Functional Hooks comparison (5/10 marks).
Ready to practice Unit 2?
You've read the core concepts. Take the balanced 10-question practice set to test your mastery!