Practical Mastery Guide

A focused resource for Practical Sample Questions and essential Viva Vocé topics.

🧪 Practical Sample Questions

1. Passing Props between Components

The standard way to pass data from a Parent to a Child component. Data flows in one direction (Unidirectional).

// 1. Parent Component (App.jsx)
function App() {
  const userName = "Alice";
  return (
    <div>
      <h1>Main App</h1>
      {/* Passing data via 'name' attribute */}
      <Child name={userName} role="Admin" />
    </div>
  );
}

// 2. Child Component (Child.jsx)
function Child(props) {
  return (
    <div className="card">
      <h3>Welcome, {props.name}!</h3>
      <p>Role: {props.role}</p>
    </div>
  );
}

2. useState Examples (Essential Patterns)

State allows components to "remember" data. When state changes, React re-renders the component.

1. Simple Counter (Numbers)
const [count, setCount] = useState(0);

// Correct way to update based on previous value
const increment = () => setCount(prev => prev + 1);

<button onClick={increment}>Count: {count}</button>
2. Input Handling (Strings)
const [user, setUser] = useState("");

<input 
  type="text" 
  value={user} 
  onChange={(e) => setUser(e.target.value)} 
  placeholder="Enter name"
/>
<p>Live Preview: {user}</p>
3. Object State (Multiple values)
const [profile, setProfile] = useState({ name: "User", age: 20 });

const updateAge = () => {
  // Use spread operator to preserve other properties (Immutability)
  setProfile({ ...profile, age: 21 });
};

3. useEffect Example (Side Effects)

Used for side-effects (API, Timers, DOM). Handles the component lifecycle: Mount -> Update -> Unmount.

useEffect(() => {
  // 1. Logic (Runs after render)
  const timer = setInterval(() => {
    console.log("OS Heartbeat...");
  }, 1000);

  // 2. Cleanup (Runs before unmount)
  return () => {
    clearInterval(timer);
    console.log("Cleaning up resources");
  };
}, []); // 3. Dependency Array: Empty = Run only once (Mount)

4. API Fetching & Rendering

Standard pattern for loading dynamic data into a component using the Fetch API.

function DataList() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(res => res.json())
      .then(json => setData(json));
  }, []);

  return (
    <ul>
      {data.slice(0, 5).map(item => <li key={item.id}>{item.title}</li>)}
    </ul>
  );
}

5. Routing in React (SPA Navigation)

Building a Single Page Application (SPA) using react-router-dom.

import { BrowserRouter, Routes, Route, Link, useNavigate, useParams } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Desktop</Link> | <Link to="/profile/user1">Profile</Link>
      </nav>

      <Routes>
        <Route path="/" element={<Desktop />} />
        <Route path="/profile/:id" element={<ProfilePage />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
}

// Example of using Params and Navigation
function ProfilePage() {
  const { id } = useParams(); // URL Params
  const navigate = useNavigate(); // Programmatic Navigation

  return (
    <div>
      <h2>User ID: {id}</h2>
      <button onClick={() => navigate('/')}>Back to Desktop</button>
    </div>
  );
}

6. Context API (Movie Context Example)

Global state management to avoid Prop Drilling.

// 1. Create the Context
const MovieContext = React.createContext();

// 2. Create the Provider (Wraps the App)
export function MovieProvider({ children }) {
  const [movies, setMovies] = useState([
    { id: 1, title: "Inception" },
    { id: 2, title: "Interstellar" }
  ]);

  return (
    <MovieContext.Provider value={{ movies, setMovies }}>
      {children}
    </MovieContext.Provider>
  );
}

// 3. Use the Context (In any child)
import { useContext } from 'react';

function MovieDisplay() {
  const { movies } = useContext(MovieContext);
  return (
    <div>
      {movies.map(movie => <li key={movie.id}>{movie.title}</li>)}
    </div>
  );
}

🎤 Essential Viva Topics

1. Project Explanation

When asked about your project (e.g., Pseudo-OS):

  • What: A React-based OS simulation with a window manager, terminal, and file explorer.
  • Tech: Built with React 18, Vite, and Lucide Icons.
  • Logic: Uses useState for window positioning and Context API for system-wide settings.

2. Synchronous vs Asynchronous

Synchronous: Code executes line by line. Each task must wait for the previous one to finish (blocking).

Asynchronous: Tasks can start now and finish later (e.g., API calls). Does not block the execution of subsequent code.

3. The Event Loop

The mechanism that allows JS to perform non-blocking I/O operations despite being single-threaded.

  • Call Stack: Where code is executed.
  • Web APIs: Where async tasks (setTimeout, Fetch) wait.
  • Callback Queue: Where finished async tasks wait to enter the stack.
  • Event Loop: Moves tasks from Queue to Stack when the Stack is empty.

4. Promises & Async/Await

Promises: An object representing the eventual completion (or failure) of an async operation.
States: Pending, Fulfilled, Rejected.
Async/Await: Syntactic sugar for Promises. Makes async code look and behave more like synchronous code.
async function getData() { const res = await fetch(...); }

5. Virtual DOM & SPA

Virtual DOM: A lightweight copy of the real DOM. React updates the Virtual DOM first, compares it (diffing), and then only updates the necessary parts of the real DOM.
SPA (Single Page Application): A web app that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a server.

📘 Theoretical Masterclass (Units 1-4)

Diffing Algorithm

The process where React compares the new Virtual DOM with the old one to identify changes.

Reconciliation

The step where React takes the identified "diffs" and updates the Real DOM to match the Virtual DOM.

One-Way Data Flow

Data in React only moves from Parent to Child via Props. This makes the app predictable and easier to debug.

Rules of Hooks
  • Call hooks only at the Top Level (Not inside loops or conditions).
  • Call hooks only from React Functions or Custom Hooks.