惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 【当耐特】
S
Schneier on Security
Blog — PlanetScale
Blog — PlanetScale
MyScale Blog
MyScale Blog
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
The GitHub Blog
The GitHub Blog
腾讯CDC
A
About on SuperTechFans
H
Help Net Security
The Register - Security
The Register - Security
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 三生石上(FineUI控件)
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Vercel News
Vercel News
V
Visual Studio Blog
T
Tailwind CSS Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - Franky
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
D
DataBreaches.Net
I
InfoQ
L
Lohrmann on Cybersecurity
M
MIT News - Artificial intelligence
I
Intezer
博客园 - 聂微东
Webroot Blog
Webroot Blog
宝玉的分享
宝玉的分享
Scott Helme
Scott Helme
Microsoft Security Blog
Microsoft Security Blog
SecWiki News
SecWiki News
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
S
Security @ Cisco Blogs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
D
Docker
N
Netflix TechBlog - Medium
小众软件
小众软件
The Cloudflare Blog
WordPress大学
WordPress大学
N
News | PayPal Newsroom
C
Check Point Blog
Google Online Security Blog
Google Online Security Blog
月光博客
月光博客
C
Cisco Blogs
阮一峰的网络日志
阮一峰的网络日志
W
WeLiveSecurity
Schneier on Security
Schneier on Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
25 React Interview Questions 2026 (With Answers) — Hooks, React 19, Concurrent Mode
Aindrila Bha · 2026-05-22 · via DEV Community

React powers the frontends of Facebook, Instagram, Netflix, Airbnb, and thousands of top tech startups. With over 40% market share among frontend frameworks, React remains the most sought-after skill for frontend developers in 2026.

Whether you're preparing for a startup loop or a FAANG panel, this comprehensive list of 25 React interview questions—updated with React 19 paradigms and modern performance patterns—will ensure you stand out.


🚀 Fundamentals (Questions 1-8)

1. What is the Virtual DOM and how does React use it?

The Virtual DOM (VDOM) is an in-memory, lightweight representation of the real browser DOM.

When a component's state or props change, React updates the Virtual DOM first. The process follows three main steps:

  1. Render: React generates a new Virtual DOM tree representing the updated UI.
  2. Reconciliation (Diffing): React compares the new Virtual DOM tree with the previous one using a highly optimized O(n) diffing algorithm.
  3. Commit: React computes the minimal set of changes needed and applies them to the real DOM (via batching), minimizing expensive layout recalculations in the browser.

2. What is JSX and why does React use it?

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like structures directly inside your JavaScript code.

JSX is not valid browser JavaScript; it must be compiled (typically using Babel or SWC) before execution. Under the hood, JSX compiles to standard function calls. In modern React (17+), JSX compiles using the automatic JSX transform:

// What you write:
const element = <h1 className="title">Hello World</h1>;

// What it compiles to:
import { jsx as _jsx } from 'react/jsx-runtime';
const element = _jsx('h1', { className: 'title', children: 'Hello World' });

Enter fullscreen mode Exit fullscreen mode

React uses JSX because it combines UI markup and rendering logic in one place, enhancing readability, developer experience (DX), and enabling compile-time syntax checks.


3. Explain the difference between controlled and uncontrolled components.

  • Controlled Components: The form input data is handled by React state. React serves as the "single source of truth" for the input values, updating the state on every keystroke.
  • Uncontrolled Components: The form data is handled directly by the browser DOM. React accesses the DOM node when needed (usually on submission) using useRef.

Controlled Component Example:

import { useState } from 'react';

function ControlledInput() {
  const [value, setValue] = useState('');

  return (
    <input 
      type="text" 
      value={value} 
      onChange={(e) => setValue(e.target.value)} 
    />
  );
}

Enter fullscreen mode Exit fullscreen mode

Uncontrolled Component Example:

import { useRef } from 'react';

function UncontrolledInput() {
  const inputRef = useRef(null);

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Input Value: ${inputRef.current.value}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={inputRef} />
      <button type="submit">Submit</button>
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

Verdict: Controlled components are preferred for most real-world scenarios because they enable instant field validation, dynamic disabling of submit buttons, and enforce predictable state.


4. What are React keys and why are they important?

Keys are unique, stable strings assigned to elements in a list. They serve as an identity card for React's reconciliation engine.

<ul>
  {items.map((item) => (
    <li key={item.id}>{item.name}</li>
  ))}
</ul>

Enter fullscreen mode Exit fullscreen mode

Why they are critical:

  • Reconciliation Guide: When list items change, are reordered, or deleted, keys tell React which specific element in the real DOM should be updated, kept, or destroyed.
  • Indices as Keys Warning: Using the array index (key={index}) as a key is an anti-pattern for dynamic lists. If list items are reordered, filtered, or inserted at the top, React will mismatch the DOM state with the component instances, causing visual glitches and rendering bugs.

5. What is prop drilling and how do you avoid it?

Prop drilling occurs when data is passed from a parent component down through multiple layers of nested child components that do not actually need the data, simply to deliver it to a deeply nested target component.

How to avoid it:

  1. Component Composition: Pass components or children down directly, keeping the state logic in the parent:

    <ParentLayout>
      <DeepChild user={user} />
    </ParentLayout>
    
  2. React Context API: Ideal for global, low-frequency state updates like themes, user authentication, or language settings.

  3. State Management Libraries: Using lightweight global stores like Zustand, Redux Toolkit, or Jotai.


6. Explain the React component lifecycle in functional components.

In modern functional React, lifecycle methods are replaced by Hooks (primarily useEffect):

  • Mounting: The component is rendered for the first time.

    useEffect(() => {
      console.log('Component mounted');
      // API calls, event listeners setup
    }, []); // Empty dependency array
    
  • Updating: The state or props of the component change, triggering a re-render.

    useEffect(() => {
      console.log('Dependency changed, component updated');
    }, [dependency]); // Runs on mount and whenever the dependency changes
    
  • Unmounting: The component is removed from the DOM.

    useEffect(() => {
      return () => {
        console.log('Component will unmount');
        // Clean up subscriptions, intervals, event listeners
      };
    }, []);
    

7. What is the difference between state and props?

Feature State Props
Definition Component's local, internal memory Data passed down from a parent component
Mutability Mutable (via updater function like setState) Immutable (read-only within the receiver)
Scope Local to the component that defined it Dynamic; controlled by the parent component
Re-render Triggers component and children to re-render Triggers component and children to re-render

8. How does React handle events differently from vanilla JavaScript?

React abstracts standard DOM events through SyntheticEvents:

  1. Cross-Browser Compatibility: React wraps native browser events in a SyntheticEvent instance, ensuring that event properties behave identically across Chrome, Safari, Firefox, and Edge.
  2. CamelCase Naming: Event handlers are named using camelCase (e.g., onClick, onSubmit) rather than lowercase (e.g., onclick, onsubmit).
  3. Event Delegation: Instead of attaching event handlers to individual DOM nodes, React attaches a single listener to the root container of your application (#root) and bubbles events up for maximum memory efficiency.

⚓ Hooks Deep Dive (Questions 9-15)

9. Explain useState vs useReducer. When would you use each?

  • useState is designed for managing simple, independent state variables (numbers, strings, booleans, or shallow objects).
  • useReducer is suited for complex state trees, multi-step forms, or state where the next state depends heavily on the previous state.

useReducer Example:

const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT': return { count: state.count + 1 };
    case 'DECREMENT': return { count: state.count - 1 };
    default: return state;
  }
};

const [state, dispatch] = useReducer(reducer, { count: 0 });

Enter fullscreen mode Exit fullscreen mode

Rule of Thumb: Use useReducer when you have 3+ interrelated state variables or when your state-updating logic starts leaking out of your component and needs to be isolated for clean testing.


10. What are the rules of hooks?

React enforces two strict rules for all Hooks:

  1. Only call Hooks at the top level: Do not call Hooks inside loops, conditional statements, or nested functions. This ensures React maps state variables in the exact same call sequence on every re-render.
  2. Only call Hooks from React functions: Call them from React functional components or custom hooks. Do not call Hooks from regular JavaScript utility functions.

Tip: Enable eslint-plugin-react-hooks in your project to automatically catch rule violations at compile time.


11. How does useEffect cleanup work?

The cleanup function is the function returned from inside your useEffect callback. It executes:

  1. Immediately before the effect re-runs (to clean up residual side effects from the previous render).
  2. When the component unmounts from the DOM.
useEffect(() => {
  const handleResize = () => console.log(window.innerWidth);
  window.addEventListener('resize', handleResize);

  // Cleanup Function:
  return () => {
    window.removeEventListener('resize', handleResize);
  };
}, []);

Enter fullscreen mode Exit fullscreen mode

Failing to clean up event listeners, WebSocket channels, or polling intervals results in memory leaks that degrade web application performance.


12. What is useMemo and when should you use it?

useMemo caches (memoizes) the computed result of an expensive calculation, recalculating it only when its specified dependency values change.

const heavyCalculation = useMemo(() => {
  return performComplexSort(dataSet);
}, [dataSet]); // Recalculates only when dataSet changes

Enter fullscreen mode Exit fullscreen mode

When to use it:

  • Heavy Computations: CPU-intensive tasks like sorting large arrays, parsing complex JSON structures, or rendering complex mathematical graphs.
  • Referential Equality: Caching object references passed down as props to children to prevent child re-renders.
  • Warning: Do not wrap every variable in useMemo. Overusing it adds garbage collection and dependency check overhead, which can actually slow down simple rendering.

13. Explain useCallback and its relationship with React.memo.

  • useCallback memoizes the function reference itself, preventing it from being re-created on every single render.
  • React.memo is a higher-order component that prevents a child component from re-rendering unless its props change.
// Parent Component
const handleButtonClick = useCallback(() => {
  console.log("Clicked!");
}, []); // Reference remains identical across renders

return <MemoizedButton onClick={handleButtonClick} />;

Enter fullscreen mode Exit fullscreen mode

Without useCallback, a standard child component wrapped in React.memo will still re-render on every parent change because inline functions are re-created with new memory references on every tick, failing shallow prop equality checks.


14. What is useRef and how does it differ from useState?

  • useRef returns a mutable object whose .current property persists throughout the lifecycle of the component. Crucially, updating .current does not trigger a component re-render.
  • useState preserves state values across renders and explicitly triggers a re-render whenever the state updater function is called.
// useRef: Perfect for capturing DOM references directly
const inputElement = useRef(null);
const focusInput = () => inputElement.current.focus();

Enter fullscreen mode Exit fullscreen mode

Use useRef when storing values that don't affect the visual output of the UI (e.g., keeping track of timer intervals, click counts, or previous state references).


15. How do you create a custom hook? Give an example.

A custom hook is a standard JavaScript function whose name starts with "use" and which calls other React hooks internally. It allows you to extract complex stateful logic out of your UI components.

Reusable Custom Fetch Hook Example:

import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    setLoading(true);

    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        if (active) {
          setData(data);
          setLoading(false);
        }
      });

    return () => {
      active = false; // Aborts stale responses
    };
  }, [url]);

  return { data, loading };
}

Enter fullscreen mode Exit fullscreen mode


⚡ Performance & Advanced (Questions 16-21)

16. How do you optimize React app performance?

When discussing optimizations, focus on these five core pillars:

  1. Code Splitting: Dynamic importing of routing pages using React.lazy() and <Suspense />.
  2. Memoization: Strategic application of React.memo(), useCallback(), and useMemo() to halt unnecessary renders.
  3. List Virtualization: Utilizing libraries like react-window or react-virtualized to only render the visible DOM nodes of a 10,000+ item list.
  4. Debouncing / Throttling: Delaying heavy search API calls or scroll listeners.
  5. State Colocation: Moving local states as close as possible to the components that actually use them to avoid sweeping parent-child re-render chains.

17. What is code splitting and how does React implement it?

Code splitting is the practice of breaking down a large, single production JavaScript bundle into multiple smaller chunks that are loaded dynamically (on-demand) as the user navigates your application.

import { lazy, Suspense } from 'react';

// Heavy component loaded lazily:
const DashboardChart = lazy(() => import('./DashboardChart'));

function App() {
  return (
    <Suspense fallback={<div>Loading Dashboard Chart...</div>}>
      <DashboardChart />
    </Suspense>
  );
}

Enter fullscreen mode Exit fullscreen mode

This reduces the initial page load time, maximizing core web vitals and overall page speeds.


18. Explain React's reconciliation algorithm.

The reconciliation algorithm determines how React updates the real DOM. Instead of comparing whole trees with O(n³) complexity, React uses heuristic rules to run at O(n) speeds:

  1. Different Element Types: If two elements have different types (e.g., swapping a <div> for a <section>), React tears down the entire subtree and mounts a completely new one from scratch.
  2. Same Element Types: If two elements have the same type, React compares the attributes/props, updates only the changed attributes, and recursively moves down to diff the children.
  3. Keys Strategy: When diffing children, React relies on keys to quickly match items in the old list with items in the new list, minimizing DOM rearrangements.

19. What are React Server Components (RSC)?

React Server Components (RSC) are a new architectural paradigm where components can render entirely on the server.

  • Server Components (Default): Render on the server, have zero impact on the client-side bundle size, can directly fetch database query results or secure API keys, and cannot use client hooks like useState or useEffect.
  • Client Components (Opt-in via "use client"): Hydrated on the client-side, fully interactive, and are free to use hooks, event listeners, and standard browser APIs.

RSCs allow you to build complex web apps with minimal client JavaScript, faster page load speeds, and improved SEO.


20. What is Suspense and how is it used in React 19?

Suspense is a built-in React component that lets you declaratively handle loading states across your application. It acts as an orchestrator, catching promises thrown by children fetching data or code-splitting.

In React 19, Suspense is deeply integrated with the framework:

  • It supports streaming server-side rendering (SSR), sending static sections to the browser immediately and hydration-streaming dynamic sections as data fetches resolve.
  • It handles resource loading (stylesheets, scripts, fonts) seamlessly, ensuring components render only after critical dependencies are ready in the browser.

21. Explain React's error boundaries.

An Error Boundary is a React component that catches JavaScript errors anywhere in its child component tree, logs the crash diagnostics, and displays a backup fallback UI instead of letting the entire web page crash blank.

Note: Error boundaries must currently be written as class components, as functional hooks do not support componentDidCatch or getDerivedStateFromError yet.

import React from 'react';

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true }; // Updates state to render fallback UI
  }

  componentDidCatch(error, errorInfo) {
    console.error("ErrorBoundary caught an error:", error, errorInfo);
  }

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

Enter fullscreen mode Exit fullscreen mode


🗃️ State Management & Patterns (Questions 22-25)

22. Compare Context API, Redux, and Zustand.

  • Context API: Built directly into React. Excellent for static or low-frequency updates (e.g., dark mode, user session). However, it is not optimized for rapid updates, as any value change forces all consumer components downstream to re-render.
  • Redux Toolkit: The classic, battle-tested standard. Strong ecosystem, middleware integration, and top-tier debugging (DevTools). However, it can be boilerplate-heavy for simple states.
  • Zustand: A modern, ultra-lightweight state manager. Based on a publish-subscribe model, it has zero boilerplate, does not wrap your app in providers, and allows hooks-based selective consumption, preventing unwanted renders.

23. What is the React Compiler (React Forget)?

The React Compiler is a new build-time tool introduced in React 19.

Traditionally, developers had to manually optimize components using useMemo, useCallback, and React.memo to avoid wasteful re-renders. The React Compiler automatically compiles your component tree at build time, injecting auto-memoization logic where it identifies that outputs won't change.

This brings the performance of hand-optimized code to standard React code without manual hook pollution.


24. Explain the render props pattern vs custom hooks.

  • Render Props Pattern: Sharing code by passing a function as a prop, letting the receiving component decide how to render details:

    <MouseTracker render={(mouse) => (
      <h1>Mouse position is: {mouse.x}, {mouse.y}</h1>
    )} />
    
  • Custom Hooks: Extracts stateful logic directly into clean functions, avoiding component nesting ("wrapper hell"):

    const { x, y } = useMousePosition();
    return <h1>Mouse position is: {x}, {y}</h1>;
    

Verdict: While render props are still useful for layout components, custom hooks are the standard choice for sharing stateful business logic.


25. How do you handle authentication in a React app?

Authentication typically follows this robust pattern:

  1. State Storage: Store the user session/JWT token in a secure global state (like a Context Provider or Zustand store).
  2. API Requests: Attach the JWT token inside HTTP headers (using an Axios Request Interceptor) for all outgoing requests.
  3. Route Protection: Wrap sensitive dashboard routes inside a ProtectedRoute component:

    function ProtectedRoute({ children }) {
      const { isAuthenticated } = useAuth();
      return isAuthenticated ? children : <Navigate to="/login" />;
    }
    
  4. Token Refreshing: Set up interceptors to automatically listen for 401 Unauthorized statuses and refresh expired tokens securely in the background.


🎯 Elevate Your Frontend Prep with MockExperts

Reading the answers is just the first step. To pass high-stakes frontend interview loops, you need to communicate these concepts clearly under pressure.

Try MockExperts' proctored AI Interview Simulator to practice live coding, dynamic React 19 system design, and behavioural rounds with instant, actionable feedback.

👉 Practice a Free Mock Interview now: MockExperts.com