Advanced Level React Interview Questions & Answers – Set 2
1. How does Next.js improve over CRA in terms of performance and SEO?
CRA only renders on client → slower first load & poor SEO (search engines see empty HTML).
Next.js can pre-render pages on server (SSR, SSG, ISR). This gives:
- Faster First Paint (HTML sent ready).
- Better SEO (search engines read full page).
- Built-in features like Image optimization, file-based routing, and code splitting.
Example:
// Next.js SSR example
export async function getServerSideProps() {
const products = await fetch("<https://api.example.com/products>").then(r => r.json());
return { props: { products } };
}
export default function Products({ products }) {
return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}
2. What is the difference between SSR, SSG, and ISR in Next.js?
-
SSR (Server-Side Rendering): HTML is generated on every request.
Example → Live stock price page.
-
SSG (Static Site Generation): HTML is generated at build time (fast, cached).
Example → Blog posts.
-
ISR (Incremental Static Regeneration): HTML is cached and refreshed after some seconds.
Example → Product catalog updated every 60s.
export async function getStaticProps() {
const data = await fetchAPI();
return { props: { data }, revalidate: 60 }; // refresh after 60s
}
3. How do you handle authentication and authorization in Next.js/React Router?
Next.js:
- Use middleware for route protection.
- Libraries:
next-auth(popular).
- React Router:
- Create a PrivateRoute that checks login before rendering.
Example:
// React Router private route example
function PrivateRoute({ children }) {
const isAuth = localStorage.getItem("token");
return isAuth ? children : <Navigate to="/login" />;
}
4. Explain dynamic imports and how they help with code splitting in React.
Dynamic import = Load a component only when needed → smaller initial bundle.
Example:
import dynamic from "next/dynamic";
const Chart = dynamic(() => import("./Chart")); // loaded only when used
5. How would you implement server-side vs client-side data fetching in Next.js?
Server-side (SSR): Fetch data on server before sending page.
export async function getServerSideProps() {
const data = await fetch("api.com");
return { props: { data } };
}
- Client-side: Fetch in
useEffectafter page loads.
function Page() {
const [data, setData] = useState([]);
useEffect(() => { fetch("api.com").then(r=>r.json()).then(setData); }, []);
}
6. How do error boundaries work under the hood? Can hooks be used inside them?
- Error Boundaries are class components with
componentDidCatchmethod. - They catch errors in child components, not in themselves.
- Hooks cannot be used inside them (must be class).
Example:
class ErrorBoundary extends React.Component {
state = { hasError: false };
componentDidCatch() { this.setState({ hasError: true }); }
render() { return this.state.hasError ? <h1>Something went wrong</h1> : this.props.children; }
}
7. How do you test React components that rely on async API calls?
- Use mocks for API calls.
- Use
findByqueries in React Testing Library (RTL).
Example:
test("loads data", async () => {
render(<UserList />);
expect(await screen.findByText("John")).toBeInTheDocument();
});
8. How do you test a component that uses hooks like useEffect or useReducer?
Just test component behavior, not hook internals.
Trigger state changes and check UI.
Example:
test("counter increments", () => {
render(<Counter />);
fireEvent.click(screen.getByText("Increment"));
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});
9. What’s the difference between shallow rendering and full rendering in testing?
- Shallow rendering: Render only component itself (no children).
- Full rendering: Render full component tree.
👉 Shallow = fast, Full = realistic.
Example:
// Shallow rendering with Enzyme
const wrapper = shallow(<MyComponent />);
10. How would you test React performance bottlenecks?
- Use React Profiler.
- Check unnecessary re-renders.
- Add
React.memo,useMemo,useCallbackwhere needed.
Example:
const Child = React.memo(({ value }) => <div>{value}</div>);
11. What is the role of lanes and priorities in React Fiber?
React Fiber assigns lanes (priority levels) to updates.
Example: User typing (high priority) > Background fetch (low priority).
Helps React decide what to render first.
12. How do you optimize a React application for First Contentful Paint (FCP)?
- Use Next.js for pre-rendering.
- Optimize images (
next/image). - Lazy load heavy components.
- Use CDN for static assets.
Example:
import Image from "next/image";
<Image src="/banner.png" width={500} height={300} priority />
13. What is the difference between hydration and re-rendering in React SSR?
- Hydration: Attach React event listeners to already-rendered HTML.
- Re-rendering: Replace DOM fully with new one.
Hydration = faster, used in SSR.
14. How does Next.js implement ISR?
- Uses cached static pages + revalidation timer.
- When timer expires → background regeneration.
- Users always see fast static page.
Example:
export async function getStaticProps() {
const posts = await fetch("...").then(r => r.json());
return { props: { posts }, revalidate: 30 }; // rebuild every 30s
}
15. What are the trade-offs of server components in React?
Pros: Smaller bundle, better performance.
Cons: No hooks (useState, useEffect), limited interactivity.
16. How do Suspense boundaries improve perceived performance?
Show fallback UI while waiting for data.
Makes app feel responsive.
Example:
<Suspense fallback={<Spinner />}>
<Profile />
</Suspense>
17. What are transitions in React 18 and how do they work?
startTransition tells React that some updates are low priority.
UI stays responsive while background work happens.
Example:
import { startTransition } from "react";
startTransition(() => setSearch(query));
18. How do you handle memory leaks in React apps?
- Clean up in
useEffect. - Cancel subscriptions, timers, event listeners.
Example:
useEffect(() => {
const id = setInterval(doWork, 1000);
return () => clearInterval(id); // cleanup
}, []);
19. What is the difference between eager loading and lazy loading in React?
- Eager: Load everything at once (fast later, slow first load).
- Lazy: Load only when needed (better initial load, may delay later).
Example:
const LazyComp = React.lazy(() => import("./HeavyComp"));
20. How do you optimize bundle size in React apps?
- Use dynamic imports.
- Remove unused libraries.
- Tree-shaking.
- Split vendor + app code.
Example:
const Map = dynamic(() => import("../components/Map"), { ssr: false });
21. How do you secure a React SPA against XSS and CSRF attacks?
- Escape all user input.
- Use
dangerouslySetInnerHTMLcarefully. - Use CSRF tokens for API calls.
- Set
Content-Security-Policyheaders.
Example:
<div>{userInput}</div> {/* safe */}
<div dangerouslySetInnerHTML={{ __html: trustedHTML }} /> {/* only trusted */}
22. How do you handle error logging in production React apps?
- Use services like Sentry, LogRocket.
- Use Error Boundaries to catch crashes and log them.
Example:
import * as Sentry from "@sentry/react";
Sentry.init({ dsn: "your-dsn" });
23. How would you implement offline support in a React app (PWA)?
- Use service workers with
workboxor CRA PWA template. - Cache assets & API responses.
Example (CRA PWA service worker):
// service-worker.js
self.addEventListener("fetch", e => {
e.respondWith(caches.match(e.request).then(res => res || fetch(e.request)));
});
24. How do you optimize React for high-frequency updates (e.g., live dashboards)?
- Use windowing/virtualization for big lists.
- Throttle or debounce updates.
- Batch updates (
unstable_batchedUpdates).
Example:
import { FixedSizeList } from "react-window";
<FixedSizeList height={400} width={300} itemSize={35} itemCount={1000}
children={({index,style}) => <div style={style}>Row {index}</div>} />
25. How would you approach scaling a large React codebase with multiple teams?
- Monorepo (Nx, Turborepo).
- Design system (Storybook).
- Module boundaries (feature-based folders).
- Shared components + libraries.
- Code reviews + linting + CI/CD.
Example (feature-based folder structure):
/src
/features
/auth
/dashboard
/profile
/shared
/components
/hooks
