1. What is React?
React is a free, open-source JavaScript library developed by Facebook (Meta) for building fast, interactive user interfaces—particularly for Single Page Applications (SPAs). Rather than structuring websites around static pages that reload on every user interaction, React dynamically updates and renders individual UI components as application data changes.
2. Traditional MPAs vs Single Page Applications (SPAs)
- Multi-Page Application (MPA): Every link clicked or form submitted sends a new request to the server, resulting in a blank screen flash while the entire HTML document reloads.
- Single Page Application (SPA): Loads a single HTML file once. When navigation or data changes occur, JavaScript intercepts the action and re-renders only the relevant portion of the screen without refreshing the browser.
3. Component-Based Architecture
In React, user interfaces are composed of modular, self-contained, and reusable building blocks called components. For example, an examination portal UI can be decomposed into:
– Top navigation bar and user profile dropdown.– Grid of numbered question buttons with color states.– Countdown clock component.– The parent container rendering questions and answers.
4. Declarative vs Imperative UI
- Imperative (Vanilla JS): You instruct the browser step-by-step on how to manipulate the DOM (e.g.,
document.getElementById("btn").classList.add("active")). - Declarative (React): You declare what the UI should look like based on current data/state, and React takes care of efficiently updating the DOM.
5. The Virtual DOM and Reconciliation
Direct DOM operations in the browser are computationally expensive. React solves this by maintaining a lightweight in-memory representation of the real DOM called the Virtual DOM (VDOM):
- When component state changes, React creates a new Virtual DOM tree.
- React compares the new Virtual DOM with the previous snapshot using a fast diffing algorithm (Reconciliation).
- React computes the minimum set of changes and batches updates to the real browser DOM, ensuring high rendering performance (60 FPS).
6. Creating a Modern React Project with Vite
Vite is the recommended modern build tool for lightning-fast React development:
# Scaffold a new React application with Vite
npm create vite@latest cbt-react-app -- --template react
# Navigate into directory and install dependencies
cd cbt-react-app
npm install
# Start local hot-reloading development server
npm run dev