Advanced React Concepts – Interview Q&A

151

What is the React Fiber architecture? Main goals?

Fiber is React's reimplementation of the core reconciler (since React 16).

Main goals:

  • Incremental rendering (ability to pause/resume/prioritize work)
  • Better support for animations & gestures
  • Concurrent mode foundation
  • Improved error boundaries & scheduling

Work units are called "fibers" — linked list instead of stack recursion.

152

What are lanes and priorities in React 18 concurrent mode?

React 18 uses a lane-based priority system instead of simple numbers.

Higher priority lanes (e.g. user input) can interrupt lower priority work (e.g. data fetching, transitions).

Enables features like:

  • startTransition / useTransition
  • useDeferredValue
  • Automatic batching in all cases
153

Explain the three main phases of React rendering (legacy vs Fiber)

In Fiber (React 16+):

  1. Render phase (may be paused/resumed) — reconciliation, building fiber tree, side-effect list
  2. Commit phase (synchronous, non-interruptible) — apply DOM changes, run layout effects
  3. Passive effects (after paint) — run useEffect callbacks

Legacy (pre-16): render → commit (all sync, blocking)

154

What is tearing and how does React 18 prevent it in concurrent mode?

Tearing = inconsistent state view during concurrent render (one part sees old state, another sees new).

React 18 prevents it via:

  • useSyncExternalStore (for external stores)
  • Consistent snapshot reads during render
  • Lane-based priority & transitions
155

Difference between automatic batching in React 17 vs React 18

Scenario React 17 React 18
Event handlers batched batched
Promises / setTimeout not batched batched
Native event handlers not batched batched
useEffect not batched batched

React 18 batches almost everything by default → fewer renders.

156

What are React Server Components (RSC)? Key characteristics

  • Render only on server → no client JS bundle for them
  • Zero hydration cost
  • Direct access to backend resources (DB, filesystem, secrets)
  • Cannot use state, effects, browser APIs, event handlers
  • Can be streamed to client
  • Marked with "use server" (Next.js) or implicitly server-rendered
157

How do client and server components interact in Next.js App Router?

  • Server Components are default
  • Client Components marked with "use client"
  • Server → Client: pass props (serializable only)
  • Client → Server: cannot import server components directly
  • Server Components can import client components (but client boundary is created)
158

What is streaming SSR and Suspense boundaries in React 18/Next.js?

Streaming = send HTML chunks as soon as they are ready instead of waiting for whole page.

<Suspense> boundaries define fallbacks and streaming chunks:

  • Non-Suspense content streams first
  • Suspense-wrapped parts stream when ready (or show fallback)

Big win for TTFB and perceived performance.

159

Explain React Compiler (React Forget) – what does it do?

Automatic memoization compiler (opt-in, experimental in 2025–2026).

Does what developers manually do with:

  • React.memo
  • useMemo
  • useCallback

Analyzes component code → memoizes props, state dependencies, and computations where safe.

Goal: remove most manual memoization boilerplate.

160

What is the most common cause of performance regressions after upgrading to React 18?

Strict mode double-invoking effects + render → exposes previously hidden side effects.

Also:

  • useEffect running more often due to new batching
  • Stale closures in concurrent mode
  • Missing cleanup functions becoming visible
161

How would you virtualize a very large list in React?

Use react-window or react-virtualized (or TanStack Virtual).

Key techniques:

  • Only render visible rows + small overscan buffer
  • Absolute positioning
  • Fixed or variable size items
  • Handle scroll / resize efficiently

Can reduce DOM nodes from 10,000 to ~30–50.

162

What are the trade-offs of using Context vs Zustand / Jotai for global state?

Context + useReducer Zustand Jotai
Boilerplate medium very low low
Re-renders all consumers on change selective (subscribe) atomic / fine-grained
DevTools basic good good
Best for small–medium theme/auth most apps very fine-grained state
163

How do you implement optimistic updates with TanStack Query (React Query)?

useMutation({
  mutationFn: updateTodo,
  onMutate: async (newTodo) => {
    await queryClient.cancelQueries({ queryKey: ['todos'] });
    const previous = queryClient.getQueryData(['todos']);
    queryClient.setQueryData(['todos'], old => [...old, newTodo]);
    return { previous };
  },
  onError: (err, newTodo, context) => {
    queryClient.setQueryData(['todos'], context.previous);
  },
  onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] })
});
164

What is the difference between invalidateQueries vs setQueryData?

Method Purpose Triggers refetch? Use when
invalidateQueries mark as stale yes (if active) after mutation, data changed on server
setQueryData immediately update cache no optimistic updates, manual cache write
165

How to debug unnecessary re-renders in React?

  1. React DevTools Profiler tab → record session → look for wasted renders
  2. Why Did You Render library (@welldone-software/why-did-you-render)
  3. console.log inside component body
  4. use React.memo + why-did-you-render on props
  5. Check props equality (new objects/functions every render?)
166

What are hydration errors? Common causes?

Hydration mismatch = server-rendered HTML differs from what client renders.

Common causes:

  • Browser-specific code (window, document) in SSR
  • Random values / Math.random() / Date.now()
  • Different timezone / locale formatting
  • Third-party scripts modifying DOM before hydration
  • Class components with unsafe lifecycles
167

How do you implement code-splitting with React.lazy + Suspense?

const About = React.lazy(() => import('./About'));

function App() {
  return (
    }>
      
        } />
      
    
  );
}

Creates separate chunk, loads on demand.

168

What is the difference between memoizing with useMemo vs React.memo?

useMemo React.memo
Targets value inside component whole component render
Compares deps array props (shallow)
Prevents re-calculation re-render
Typical for expensive derived data list items, pure UI components
169

How do you handle errors in React Server Components?

Use error.js file in Next.js App Router (convention-based).

For manual handling:

  • Throw error in RSC → caught by nearest error boundary
  • notFound() / redirect() for expected cases
170

What is the role of loading.js in Next.js App Router?

Automatically wraps page / segment in Suspense with the loading UI.

Shows instantly while server component / data fetches are pending.

Improves perceived performance (shows skeleton / spinner early).

171

How do you type custom hooks with TypeScript?

function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void] {
  // implementation
}

Or more advanced with generics + type inference from default value.

172

What are compound components? Modern implementation pattern

Components that share implicit state via context (Tabs, Accordion, Select, Dialog).

Modern style (2025):

<Tabs>
  <Tabs.List>...</Tabs.List>
  <Tabs.Content value="1">...</Tabs.Content>
</Tabs>

Implemented with custom context + provider.

173

How to test components that use useEffect with fake timers?

Use jest.useFakeTimers() + act:

jest.useFakeTimers();
render(<MyComponent />);
act(() => jest.advanceTimersByTime(1000));
expect(screen.getByText('done')).toBeInTheDocument();
174

What is the purpose of startTransition vs useTransition?

startTransition = low-level API to wrap any state update as transition.

useTransition = hook version that also gives isPending flag.

Use startTransition outside components (e.g. libraries).

175

How do you prevent prop drilling in very deep trees without Context?

  • Component composition (children, render props)
  • Pass components as props (slot pattern)
  • CloneElement + extra props
  • Wrapper components that inject behavior

Context still most common for truly global data.

176

What is the difference between getServerSideProps vs getStaticProps (legacy) vs App Router patterns?

Pages Router (legacy):

  • getStaticProps → static at build time
  • getServerSideProps → SSR per request
  • getStaticPaths → dynamic static paths

App Router (modern):

  • Server Components + async/await in component
  • fetch with { cache: 'no-store' } = SSR
  • fetch with { next: { revalidate: 3600 } } = ISR
  • Static by default
177

How to implement infinite scrolling with TanStack Query?

const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
  queryKey: ['posts'],
  queryFn: ({ pageParam = 1 }) => fetchPosts(pageParam),
  getNextPageParam: (lastPage) => lastPage.nextCursor,
});

Use IntersectionObserver on last item to call fetchNextPage.

178

What are the main advantages of TanStack Query over useEffect + fetch?

  • Automatic caching
  • Background refetching & stale-while-revalidate
  • Deduping requests
  • Pagination & infinite queries built-in
  • Optimistic updates & rollback
  • Devtools & error handling
  • Less race conditions
179

How do you handle race conditions when fetching data on user input?

  • Debounce / throttle input
  • Use abort controller + cleanup in useEffect
  • TanStack Query handles it automatically (latest request wins)
  • Track request ID and ignore old responses
180

What is the benefit of using React Server Actions over API routes?

  • Progressive enhancement (works without JS)
  • Direct server functions (no endpoint needed)
  • Automatic pending state & optimistic UI with useActionState
  • Simpler revalidation (revalidatePath, revalidateTag)
  • FormData support built-in
181

How do you optimize images in Next.js (2025–2026 best practices)?

  • Use built-in <Image> component
  • Automatic WebP / AVIF conversion
  • Lazy loading & placeholders (blur, empty)
  • Sizes attribute for responsive
  • Remote images with loader config
  • Image Optimization API caching
182

What is the difference between revalidatePath vs revalidateTag?

revalidatePath revalidateTag
Granularity path / route cache tag
Use case after form submit affecting page multiple pages share same data
Impact re-renders layout + page only tagged fetches
183

How do you implement authentication in Next.js App Router?

Common patterns 2025–2026:

  • NextAuth.js / Auth.js
  • Server-side session check in middleware
  • Protect routes with middleware or layout
  • RSC: read cookies / headers directly
  • Client: useSession hook
  • Server Actions: verify session before mutation
184

What are partial prerendering (PPR) in Next.js?

Hybrid rendering: static shell + dynamic holes filled at request time.

Static parts cached, dynamic parts (Suspense boundaries) rendered per request.

Combines best of SSG + SSR + streaming.

Available in Next.js 14+ (stable in 15).

185

How do you handle SEO in React SPA vs Next.js?

SPA (Create React App / Vite):

  • Prerendering tools (prerender.io, react-snap)
  • Server-side prerendering services
  • Bad for crawlers without JS

Next.js:

  • Static export / SSG
  • SSR / ISR
  • Metadata API / generateMetadata
  • Open Graph / Twitter cards automatic
186

What is the purpose of generateStaticParams in Next.js App Router?

Replaces getStaticPaths — defines dynamic routes to prerender at build time.

export async function generateStaticParams() {
  const posts = await getPosts();
  return posts.map(post => ({ slug: post.slug }));
}
187

How do you implement dark mode in React / Next.js (2025 best way)?

  • next-themes or custom context + localStorage + useEffect
  • CSS variables + class on html / body
  • prefers-color-scheme media query
  • Server component reads cookie → passes initial theme
  • Client toggle updates cookie + class
188

What are the main causes of hydration mismatch warnings?

  • Browser APIs (window, document) during SSR
  • Date / random values differing server vs client
  • Third-party scripts modifying DOM early
  • useEffect setting state on mount
  • Different component tree structure
189

How do you profile React performance in production?

  • React DevTools Profiler (development only)
  • Chrome Performance tab → flamegraph
  • Why Did You Render in production (with tracking)
  • Web Vitals (CLS, LCP, FID/INP)
  • Next.js next build + next start + analytics
190

What is Incremental Static Regeneration (ISR)? How to use in Next.js?

Static page regenerated in background after time interval while serving stale version.

App Router: fetch(..., { next: { revalidate: 3600 } })

Pages Router: getStaticProps with revalidate: 60

191

How do you handle SEO metadata dynamically in App Router?

export async function generateMetadata({ params }) {
  const post = await getPost(params.slug);
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: { images: post.ogImage }
  };
}
192

What is the difference between dynamic = 'force-dynamic' vs 'force-static'?

Option Behavior Use case
force-dynamic SSR every request personalized, real-time data
force-static SSG at build static landing pages, docs
default (auto) static if no dynamic APIs used most pages
193

How do you implement middleware in Next.js for auth / redirects?

import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.cookies.get('token')?.value;
  if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ['/dashboard/:path*'] };
194

What are the main differences between Zustand and Redux Toolkit in 2026?

Aspect Zustand Redux Toolkit
Boilerplate minimal moderate (but RTK Query helps)
Bundle size very small (~1–2 KB) larger
DevTools good excellent (time-travel)
Best for most apps, simplicity large teams, complex async, enterprise
196

What is the recommended way to handle forms in Next.js 14+ / React 19?

  • Server Actions + useActionState (React 19)
  • React Hook Form + Zod + Server Actions
  • Form + action attribute pointing to Server Action
  • Optimistic updates with useOptimistic
197

How do you measure and improve Cumulative Layout Shift (CLS)?

  • Reserve space for images / ads (width, height, aspect-ratio)
  • Use Next.js <Image> with fill / sizes
  • Avoid injecting content above existing content
  • Font loading: use font-display: swap or self-host
  • Monitor with Lighthouse / Web Vitals
198

What are the main benefits of using TanStack Router vs Next.js routing?

  • Full type-safety (search params, route params)
  • Client-side only routing (SPA feel)
  • Built-in data loading & pending states
  • Less server dependency
  • Great for complex apps with nested layouts

Next.js still wins for SEO + SSR.

199

How do you implement role-based access control (RBAC) in Next.js?

  • Middleware checks session + role → redirect if unauthorized
  • Server Components: check role before rendering sensitive content
  • Client: hide UI elements based on role (but never trust client)
  • Server Actions: verify role before mutation
200

What are the top 5 React performance rules in 2026?

  1. Avoid new object/function references in render (useMemo, useCallback wisely)
  2. Use React.memo + stable props for list items & pure components
  3. Virtualize long lists (react-window / TanStack Virtual)
  4. Leverage Server Components + streaming + Suspense
  5. Profile first — don't premature optimize; React Compiler reduces manual work