50 Topics
Chapter•300 Minutes

Part 2 - Complete React.js Progressive Master Question Bank

50 progressive React.js interview questions covering JSX compilation, Virtual DOM & Fiber architecture, Hooks internals, state management, SSR/RSC, and performance profiling.

Q1: What is the Virtual DOM and how does Reconciliation work in React?

The Virtual DOM (VDOM) is an in-memory lightweight JS object representation of the real DOM. When state or props change, React creates a new Virtual DOM tree and runs a diffing algorithm during Reconciliation to calculate the minimal set of real DOM operations required.

React Virtual DOM Reconciliation Lifecycle
Virtual DOM Representation Example
// What JSX converts into (Virtual DOM Node object)
const vdomNode = {
  type: 'button',
  props: {
    className: 'btn-primary',
    onClick: () => console.log('Clicked'),
    children: 'Submit'
  }
};

JSX elements compile to plain JS objects describing element node type, properties, event listeners, and children.

Key Takeaways
  • Virtual DOM minimizes direct real DOM manipulations to boost rendering performance.

  • React uses a heuristics O(n) diffing algorithm during Reconciliation to compute minimal real DOM updates.

Knowledge Check

What is the primary benefit of React's Virtual DOM Reconciliation process?

Q2: What is React Fiber and how does it improve application responsiveness?

React Fiber is the re-implementation of React's core reconciliation algorithm introduced in React 16. It breaks rendering work into incremental units of work called Fiber nodes, enabling React to pause, resume, assign priority to, or abandon work as higher-priority user inputs arrive.

Fiber Priority Work Scheduler
Priority Work Interruption Model
// Fiber tree structure snippet (Internal React Node Representation)
const fiberNode = {
  type: 'div',
  child: childFiberNode,
  sibling: siblingFiberNode,
  return: parentFiberNode,
  pendingProps: nextProps,
  lanes: PriorityLanes // Tracks execution priority
};

Fiber nodes use child, sibling, and return pointers to traverse trees iteratively without locking the JS call stack.

Key Takeaways
  • Replaces synchronous stack reconciliation with asynchronous cooperative scheduling.

  • Enables time-slicing and priority-based scheduling for smooth 60fps user interactions.

Knowledge Check

Which phase of Fiber execution is interruptible by higher-priority tasks?

Q3: How is JSX compiled under the hood in modern React?

JSX is a syntax extension for JavaScript. It does not run natively in browsers. Compilers like Babel transform JSX tags into React.createElement() calls (or _jsxRuntime.jsx() in React 17+ JSX transform) that return plain Virtual DOM objects.

JSX to JS Compilation Comparison
// 1. Input JSX
const element = <h1 className="title">Hello World</h1>;

// 2. Output (Compiled JS via Babel React 17+ Runtime)
import { jsx as _jsx } from 'react/jsx-runtime';
const element = _jsx('h1', { className: 'title', children: 'Hello World' });

Compilers translate declarative JSX syntax into functional call trees creating React element descriptors.

Key Takeaways
  • JSX is syntactic sugar for React.createElement() or _jsx() calls.

  • Modern JSX transform eliminates the need to explicitly import React in every file.

Knowledge Check

What does a JSX tag <MyComponent /> evaluate to after compilation?

Q4: What is the fundamental difference between State and Props?

Props (short for properties) are read-only input parameters passed down from a parent component to a child component. State is internal data managed locally within a component that can change over time in response to user actions or network events, triggering re-renders.

Props vs State Usage
function CounterContainer() {
  const [count, setCount] = useState(0); // Local State
  return <CounterDisplay value={count} onIncrement={() => setCount(count + 1)} />; // Passed as Props
}

function CounterDisplay({ value, onIncrement }) {
  return <button onClick={onIncrement}>Count: {value}</button>;
}

CounterContainer owns the count state and passes it down alongside updater callbacks as props to CounterDisplay.

Key Takeaways
  • Props flow unidirectionally downward and are immutable by the child component.

  • State is local, mutable via state updater functions, and triggers re-renders on update.

Knowledge Check

What happens if a child component attempts to reassign props.title = 'New Title' directly?

Q5: Why are 'keys' required when rendering lists in React, and why avoid index keys?

Keys give items in a list a stable identity. React uses keys during the reconciliation diffing process to identify which items were added, updated, or removed. Using array indices as keys can lead to subtle rendering bugs, input state corruption, and sub-optimal reconciliation if list items are reordered or filtered.

Unique ID Key Mapping
function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        // RECOMMENDED: Unique item ID key
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

Using a unique todo.id ensures React preserves component state correctly when list items move.

Key Takeaways
  • Keys allow React to match Virtual DOM list nodes across re-renders efficiently.

  • Avoid array indices as keys when items can be reordered, inserted, or removed.

Knowledge Check

What issue occurs when using array indices as keys for a dynamic reorderable list?

Q6: How does useState work internally and why is state batching used?

useState stores state variables inside the component Fiber node's linked list of hooks. Calling a state setter function enqueues a update action on the Fiber queue. React batches multiple state updates within event handlers into a single re-render cycle to optimize performance.

Functional State Updates & Automatic Batching
function Counter() {
  const [count, setCount] = useState(0);

  const handleMultipleIncrements = () => {
    // Functional updates queue operations on Fiber state queue
    setCount(prev => prev + 1);
    setCount(prev => prev + 1);
    // React batches these calls into a single component re-render pass
  };
  return <button onClick={handleMultipleIncrements}>Count: {count}</button>;
}

Functional state updates evaluate sequentially against the queued Fiber state, updating count safely to 2.

Key Takeaways
  • Hook states are preserved inside a linked list attached to the component Fiber instance.

  • Automatic batching (React 18) combines multiple state updates into single re-render updates.

Knowledge Check

Why should you pass a callback function to setState (setCount(prev => prev + 1)) when new state depends on previous state?

Q7: How does useEffect manage side-effects, dependencies, and cleanup cycles?

useEffect executes side-effects after the component renders and DOM updates are committed. The dependency array controls when the effect executes: omitting it runs after every render, an empty array [] runs once on mount, and passing dependencies [a, b] runs when specified variables change. Returning a function triggers cleanup before re-executing or unmounting.

useEffect Execution & Cleanup Lifecycle
useEffect Subscription & Cleanup Pattern
useEffect(() => {
  const subscription = api.subscribeToData(id);
  
  // Cleanup closure function
  return () => {
    subscription.unsubscribe();
  };
}, [id]); // Re-subscribes if 'id' changes

The returned unsubscribe function runs before re-subscribing on id change or when the component unmounts.

Key Takeaways
  • Runs asynchronously after paint to prevent blocking browser rendering.

  • Cleanup function executes prior to effect re-execution and component unmounting.

Knowledge Check

When does the cleanup function returned inside useEffect execute?

Q8: What are the Rules of Hooks and why are they enforced?

  1. Only call Hooks at the Top Level: Don't call Hooks inside loops, conditions, or nested functions.
  2. Only call Hooks from React Functions: Call Hooks from Functional Components or Custom Hooks. Enforced because React relies on the exact execution order of Hooks across re-renders to map state variables to internal Fiber linked list nodes.
Rules of Hooks Violation vs Correct Pattern
// ❌ BAD: Conditional Hook call alters Hook execution order
if (isLoggedIn) {
  useEffect(() => fetchUserData(), []);
}

// ✅ GOOD: Keep Hook top-level, move condition inside Hook
useEffect(() => {
  if (isLoggedIn) {
    fetchUserData();
  }
}, [isLoggedIn]);

Keeping useEffect at the top level guarantees that Hook index pointers match internal Fiber node linked lists.

Key Takeaways
  • React tracks Hook states using an ordered linked list on the Fiber node.

  • Conditional Hook calls alter execution order, mismatching state bindings.

Knowledge Check

Why does calling a Hook inside an IF statement break React applications?

Q9: What is the difference between useMemo and useCallback?

  • useMemo: Caches the result value of an expensive calculation (useMemo(() => computeValue(a), [a])).
  • useCallback: Caches the function instance itself between re-renders (useCallback(() => handleClick(), [])) to prevent breaking child component React.memo reference equality checks.
useMemo vs useCallback Usage
// Memoize calculated result value
const expensiveValue = useMemo(() => {
  return calculateBigData(data);
}, [data]);

// Memoize callback function reference pointer
const handleAction = useCallback(() => {
  console.log('Action performed for id:', id);
}, [id]);

useMemo skips re-calculating big data when data is unchanged; useCallback maintains identical handleAction references.

Key Takeaways
  • useMemo memoizes computed return values.

  • useCallback memoizes function reference pointers across renders.

Knowledge Check

What primary performance issue does useCallback solve when passing functions to memoized child components?

Q10: What is useRef and how does it differ from useState?

useRef returns a mutable object { current: initialValue } whose reference persists across re-renders. Modifying ref.current does not trigger a component re-render. It is used to access direct DOM nodes or store instance variables that shouldn't cause UI updates when mutated.

DOM Focus Control with useRef
function TextInputWithFocus() {
  const inputEl = useRef(null);
  
  const onButtonClick = () => {
    // Imperative focus targeting
    inputEl.current.focus();
  };
  
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus Input</button>
    </>
  );
}

inputEl.current references the underlying native HTMLInputElement node directly.

Key Takeaways
  • Mutating .current updates values synchronously without causing a re-render.

  • Commonly used for imperative DOM access (focus, canvas, media playback) and timer IDs.

Knowledge Check

What happens to the UI component when you assign timerRef.current = setTimeout(...) inside a click handler?

Q11: How does the React Context API work and how do you prevent Context render thrashing?

Context provides a mechanism to pass data through the component tree without manually passing props at every level ('prop drilling'). However, whenever a Context Provider value object updates, all consuming components re-render. To avoid render thrashing, split contexts by domain or memoize provider values with useMemo.

Memoizing Context Provider Values
function UserProvider({ children }) {
  const [user, setUser] = useState(null);

  // Memoize value to prevent consumer re-renders when parent re-renders
  const contextValue = useMemo(() => ({ user, setUser }), [user]);

  return (
    <UserContext.Provider value={contextValue}>
      {children}
    </UserContext.Provider>
  );
}

useMemo ensures contextValue maintains reference equality unless user state explicitly updates.

Key Takeaways
  • Eliminates deep prop drilling across component hierarchies.

  • Unmemoized value objects (value={{ state, dispatch }}) create fresh references every render, forcing consumers to re-render.

Knowledge Check

What causes all components calling useContext(MyContext) to re-render?

Q12: How does React.memo optimize component rendering performance?

React.memo is a higher-order component (HOC) that memoizes function component rendering outcomes. It skips re-rendering the component if incoming props have not changed according to a shallow comparison (Object.is).

React.memo Component Wrapper
const ExpensiveChild = React.memo(function Child({ title }) {
  console.log('Child Rendered');
  return <h2>{title}</h2>;
});

// Custom comparison optional second parameter
const CustomMemoChild = React.memo(Child, (prevProps, nextProps) => {
  return prevProps.id === nextProps.id;
});

ExpensiveChild skips re-execution when parent re-renders if title prop remains strictly unchanged.

Key Takeaways
  • Performs shallow prop comparison before granting re-renders.

  • Can accept a custom comparison function React.memo(Component, arePropsEqual).

Knowledge Check

What comparison technique does React.memo use by default on incoming component props?

Q13: What are Custom Hooks and what problem do they solve?

Custom Hooks are JavaScript functions whose names start with use that can call other React Hooks. They allow extracting and sharing stateful logic across multiple components without altering component hierarchy structures (unlike older Render Props or HOC patterns).

Custom Window Width Hook
function useWindowSize() {
  const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight });
  
  useEffect(() => {
    const handleResize = () => setSize({ width: window.innerWidth, height: window.innerHeight });
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return size;
}

Components using useWindowSize() encapsulate window resize listener subscriptions cleanly.

Key Takeaways
  • Extracts reusable stateful logic without duplicating code.

  • State inside custom hooks is isolated per component instance.

Knowledge Check

If two separate components call the same custom hook useFetchData(), do they share state variables?

Q14: How do React Synthetic Events work and how do they differ from native DOM events?

React wraps browser native events inside cross-browser SyntheticEvent wrapper instances to guarantee property consistency across browsers. React uses Event Delegation, attaching single top-level event listeners to the root DOM container (#root in React 17+) rather than attaching listeners to individual DOM nodes.

Accessing Native Events from Synthetic Events
function FormComponent() {
  const handleSubmit = (event) => {
    event.preventDefault(); // SyntheticEvent method
    console.log('Native Event Target:', event.nativeEvent.target); // Access underlying native DOM event
  };
  return <form onSubmit={handleSubmit}><button>Submit</button></form>;
}

event is a SyntheticEvent object, while event.nativeEvent exposes the underlying browser DOM Event object.

Key Takeaways
  • Cross-browser normalized event wrapper around browser native events.

  • Uses Event Delegation registered at the root React DOM container.

Knowledge Check

Where does React 17+ attach event listeners under its Event Delegation model?

Q15: What are Error Boundaries and what types of errors can they catch?

Error Boundaries are React Class Components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI. They catch errors during rendering, lifecycle methods, and constructors. They do NOT catch errors in event handlers, async code, SSR, or unhandled promise rejections.

Class Error Boundary Implementation
class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true }; // Render fallback UI
  }

  componentDidCatch(error, errorInfo) {
    logErrorToService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) return <h1>Something went wrong.</h1>;
    return this.props.children;
  }
}

Wrapping components inside ErrorBoundary safely catches rendering errors and displays fallback UI.

Key Takeaways
  • Defined using class methods static getDerivedStateFromError() or componentDidCatch().

  • Prevents whole component tree unmounting due to uncaught rendering errors.

Knowledge Check

Which type of error CANNOT be caught by a React Error Boundary?

Q16: What is the difference between Controlled and Uncontrolled Components?

  • Controlled Component: Form input state is driven by React state (value + onChange). React acts as the 'single source of truth'.
  • Uncontrolled Component: Form input state is handled directly by the browser DOM. React reads input values imperatively using a useRef pointer.
Controlled vs Uncontrolled Forms
// Controlled
const [val, setVal] = useState('');
<input value={val} onChange={e => setVal(e.target.value)} />

// Uncontrolled
const inputRef = useRef();
<input ref={inputRef} defaultValue="Initial" />

Controlled inputs store text inside React state; uncontrolled inputs leave data storage to the DOM element.

Key Takeaways
  • Controlled components provide instant validation and dynamic input control.

  • Uncontrolled components offer simpler integration for heavy file inputs or legacy forms.

Knowledge Check

Which form input type in HTML is always inherently an Uncontrolled Component in React?

Q17: What are React Portals and when should you use them?

Portals (ReactDOM.createPortal(child, container)) provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. Used for modals, tooltips, and popovers to bypass CSS z-index and overflow: hidden parent clipping.

Rendering Modal via Portal
import ReactDOM from 'react-dom';

function Modal({ children }) {
  return ReactDOM.createPortal(
    <div class="modal-overlay">{children}</div>,
    document.getElementById('modal-root') // Mounted to body root
  );
}

Modal renders inside #modal-root at the body level while retaining React parent-child context and event bubbling.

Key Takeaways
  • Renders HTML DOM output outside parent containers.

  • Events dispatched inside portals still bubble up through the React Virtual DOM component tree.

Knowledge Check

Does a click event originating inside a React Portal bubble up to its parent component in the React VDOM tree?

Q18: What is a Higher-Order Component (HOC) and how does it compare to Render Props?

A Higher-Order Component is a pure function that takes a component as an argument and returns an enhanced new component (const EnhancedComp = withFeature(WrappedComp)). Render Props passes a render function prop to delegate UI rendering. Both patterns share component logic, though Custom Hooks have largely superseded them.

HOC Wrapper Pattern
function withAuthentication(WrappedComponent) {
  return function AuthenticatedComponent(props) {
    const { isAuthenticated } = useAuth();
    if (!isAuthenticated) return <p>Access Denied</p>;
    return <WrappedComponent {...props} />;
  };
}

withAuthentication wraps components with auth authorization checks before rendering child components.

Key Takeaways
  • HOC: Component => EnhancedComponent pattern.

  • Avoid mutating original wrapped components; pass unhandled props through.

Knowledge Check

What common issue can occur when chaining multiple HOC wrappers together?

Q19: When should you use useReducer instead of useState?

useReducer is preferable for complex state logic involving multiple sub-values, nested state updates, or where the next state depends on the previous state across multiple user actions. It follows the Redux-like pattern (state, action) => newState.

useReducer State Machine
const initialState = { count: 0 };
function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    case 'decrement': return { count: state.count - 1 };
    default: throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return <button onClick={() => dispatch({ type: 'increment' })}>{state.count}</button>;
}

useReducer centralizes action updates inside pure functions, decoupling UI interactions from state mutation rules.

Key Takeaways
  • Centralizes complex state update logic into a pure reducer function.

  • Passes stable dispatch function pointers down to optimize child renders.

Knowledge Check

Is the dispatch function reference returned from useReducer guaranteed to be stable across re-renders?

Q20: Why does React StrictMode render components twice in development?

<React.StrictMode> intentionally double-invokes component renders, useState updaters, and useEffect setup/cleanup functions in development mode only. This helps surface accidental side-effects during render phases, impure functions, and missing effect cleanups.

Wrapping Application in StrictMode
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

const root = createRoot(document.getElementById('root'));
root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

StrictMode double-runs development mounts to ensure setup and cleanup cycles are completely symmetrical.

Key Takeaways
  • Only active in Development builds; has zero performance impact in Production.

  • Surfaces side-effect bugs, impure renders, and uncleaned async subscriptions.

Knowledge Check

Does React StrictMode double-render components in Production environment builds?

Q21: What are React 18 Concurrent Features (useTransition, useDeferredValue)?

Concurrent React allows React to pause, resume, and execute multiple component tree renders simultaneously. - useTransition: Marks state updates as non-urgent transitions, keeping UI responsive to clicks/typing.

  • useDeferredValue: Defers updating non-critical UI subtrees based on heavy values.
useTransition Non-Urgent Update
function SearchApp() {
  const [isPending, startTransition] = useTransition();
  const [filterTerm, setFilterTerm] = useState('');

  const handleChange = (e) => {
    // Urgent update: Update input field text immediately
    setInputValue(e.target.value);
    
    // Non-urgent transition: Render heavy filtered list in background
    startTransition(() => {
      setFilterTerm(e.target.value);
    });
  };
}

startTransition marks setFilterTerm as interruptible background work, leaving input text typing responsive.

Key Takeaways
  • Differentiates urgent updates (typing, clicking) from non-urgent transitions (filtering lists).

  • Prevents main thread locking during heavy render passes.

Knowledge Check

Which Hook marks a state update as a non-urgent transition to prevent locking user typing input?

Q22: What is the difference between useEffect and useLayoutEffect?

  • useEffect: Runs asynchronously after the DOM updates are committed and screen paint completes. Prevents blocking browser painting.
  • useLayoutEffect: Runs synchronously after DOM updates are committed but before the browser paints the screen. Use strictly to measure DOM geometry and prevent visual layout flicker.
DOM Measurement with useLayoutEffect
useLayoutEffect(() => {
  // Read DOM measurements synchronously before browser paint
  const { height } = ref.current.getBoundingClientRect();
  setElementHeight(height);
}, []);

Measuring and updating state inside useLayoutEffect prevents visual layout flickering before screen paint.

Key Takeaways
  • useLayoutEffect blocks browser paint until execution completes.

  • Use useLayoutEffect to read DOM dimensions and apply scroll positioning before user visual paint.

Knowledge Check

Which effect Hook should be chosen if updating state causes visible screen element flickering when using useEffect?

Q23: How does React.lazy and Suspense enable route-based code splitting?

React.lazy() allows rendering dynamic imports as standard components. Suspense wraps dynamic components and displays a fallback UI (like a loader spinner) while bundle JS chunks download asynchronously over the network.

Route-Based Code Splitting
import React, { Lazy, Suspense } from 'react';

// Dynamic JS import bundle chunk
const AdminDashboard = React.lazy(() => import('./AdminDashboard'));

function App() {
  return (
    <Suspense fallback={<Spinner />}>
      <AdminDashboard />
    </Suspense>
  );
}

AdminDashboard bundle chunk downloads only when route renders, displaying Spinner in the interim.

Key Takeaways
  • Splits large JavaScript bundles into smaller route chunks.

  • Suspense handles pending promise states cleanly using fallback props.

Knowledge Check

What happens if a React.lazy component fails to load due to a network bundle error?

Q24: How does Redux Toolkit compare against lightweight stores like Zustand?

  • Redux Toolkit (RTK): Enforces structured unidirectional data flow, explicit actions, immutability via Immer, middleware support, and RTK Query for caching. Great for enterprise applications.
  • Zustand: Minimalist, un-opinionated state store operating on plain hooks without boilerplate action boilerplate, context providers, or heavy wrappers.
Zustand Hook Store Example
import { create } from 'zustand';

const useStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
}));

function BearCounter() {
  const bears = useStore((state) => state.bears);
  return <h1>{bears} Bears</h1>;
}

Zustand allows components to select specific store state selectors directly without Provider wrappers.

Key Takeaways
  • RTK provides rigid structural patterns, Redux DevTools tracing, and data fetching.

  • Zustand provides hook-based state stores with zero provider wrapper requirement.

Knowledge Check

Does Zustand require wrapping the root component tree in a Context Provider?

Q25: What are React Server Components (RSC) and how do they differ from Client Components?

React Server Components (RSC) run exclusively on the server during request or build execution. They don't ship JavaScript bundle bytes to the client, can query databases directly, and cannot use state or effects. Client Components ('use client') ship JS bundles to browser engines and handle interactive events, state, and DOM effects.

RSC vs Client Component Architecture
React Server Component Direct DB Query
// Default: Server Component in Next.js App Router (No 'use client')
import db from '@/lib/db';

export default async function Page() {
  // Direct database query on server without API endpoints
  const posts = await db.query('SELECT * FROM posts');
  return <ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>;
}

Server Components execute database calls directly on Node.js servers, streaming HTML layout to browsers.

Key Takeaways
  • RSCs reduce client JS bundle sizes to zero bytes for server components.

  • Client components ('use client') handle interactivity, state, and browser APIs.

Knowledge Check

Which React feature allows calling useState() or onClick event listeners inside a Next.js App Router component?

Q26: What is forwardRef and useImperativeHandle, and when should you use them?

forwardRef allows a component to pass a ref down to a child component. useImperativeHandle works with forwardRef to customize the imperative handle (methods/properties) exposed to the parent component, hiding internal implementation details.

Custom Imperative Methods via useImperativeHandle
const CustomInput = forwardRef((props, ref) => {
  const inputRef = useRef();
  
  useImperativeHandle(ref, () => ({
    focusInput: () => inputRef.current.focus()
  }));
  
  return <input ref={inputRef} />;
});

Parent components calling ref.current.focusInput() execute the custom imperative handle.

Key Takeaways
  • forwardRef passes refs down through child functional components.

  • useImperativeHandle limits exposed imperative methods (e.g. exposing .focus() instead of full DOM element).

Knowledge Check

What is the main reason to pair useImperativeHandle with forwardRef?

Q27: What causes React Hydration Mismatch errors during SSR and how do you fix them?

A Hydration error occurs when the pre-rendered HTML string generated on the server doesn't match the initial Virtual DOM tree generated during client-side hydration. Caused by using window checks, Date.now(), or Math.random() directly during render execution.

Fixing Hydration Differences
function DateDisplay() {
  const [formattedDate, setFormattedDate] = useState('');

  useEffect(() => {
    // Safely update on client after hydration completes
    setFormattedDate(new Date().toLocaleDateString());
  }, []);

  return <span>{formattedDate}</span>;
}

Deferring browser-specific date calculations to useEffect prevents SSR HTML mismatch failures.

Key Takeaways
  • Server HTML and initial Client Virtual DOM tree must be identical.

  • Fix by deferring browser-only values to useEffect or disabling SSR using dynamic imports.

Knowledge Check

Why does rendering typeof window !== 'undefined' ? 'Mobile' : 'Desktop' directly in JSX trigger a Hydration error?

Q28: How do you profile and debug unnecessary re-renders using React DevTools Profiler?

The React DevTools Profiler records component render metrics. It classifies renders using Flamecharts and Ranked charts, highlighting why each component rendered (e.g., 'Props changed', 'State changed', or 'Parent component rendered').

Programmatic Profiler API Usage
import { Profiler } from 'react';

function onRenderCallback(id, phase, actualDuration) {
  console.log(`[${id}] ${phase} phase took ${actualDuration}ms`);
}

<Profiler id="Navigation" onRender={onRenderCallback}>
  <NavigationComponent />
</Profiler>

The Profiler component records exact render execution duration and phase lifecycle details.

Key Takeaways
  • Profiler pinpoints render durations and root causes.

  • Look for 'Parent component rendered' to identify components missing React.memo.

Knowledge Check

In React DevTools Profiler, what does 'Parent component rendered' mean under render reason?

Q29: How do you implement Optimistic UI updates with the useOptimistic Hook in React 19?

React 19's useOptimistic hook allows immediately displaying an optimistic state result to users while a server background mutation is pending. If the network request fails, React rolls back the state automatically.

React 19 useOptimistic Hook Usage
import { useOptimistic } from 'react';

function Thread({ messages, sendMessage }) {
  const [optimisticMessages, addOptimisticMessage] = useOptimistic(
    messages,
    (state, newText) => [...state, { text: newText, sending: true }]
  );

  const formAction = async (formData) => {
    const text = formData.get('message');
    addOptimisticMessage(text); // Immediately update UI
    await sendMessage(text);     // Perform actual network mutation
  };
}

useOptimistic immediately appends the pending message to state while sendMessage executes.

Key Takeaways
  • Improves perceived latency by rendering expected mutation responses immediately.

  • Rolls back state safely if the background network action fails.

Knowledge Check

What primary user experience benefit does Optimistic UI provide?

Q30: How does the useActionState Hook manage form submission state in React 19?

useActionState (formerly useFormState) simplifies form handling by accepting an async action function and returning the updated state, form action trigger, and a isPending status flag.

useActionState Form Submission
import { useActionState } from 'react';

async function updateNameAction(previousState, formData) {
  const name = formData.get('name');
  return await api.updateName(name);
}

function Profile() {
  const [state, formAction, isPending] = useActionState(updateNameAction, null);
  return (
    <form action={formAction}>
      <input name="name" />
      <button disabled={isPending}>Save</button>
      {state?.error && <p>{state.error}</p>}
    </form>
  );
}

useActionState manages isPending states and server action responses without manual useState calls.

Key Takeaways
  • Handles pending status, server responses, and form errors natively.

  • Integrates seamlessly with Server Actions and HTML <form action> elements.

Knowledge Check

Which flag returned from useActionState indicates that a form Server Action is actively pending?