🚀 React Interview Questions & Answers

Comprehensive guide covering hooks, performance optimization, state management, and advanced React concepts

1. What is the purpose of `useCallback` hook in React?

useCallback is a hook that returns a memoized version of a callback function. It prevents the function from being recreated on every render, which is useful when passing callbacks to child components to avoid unnecessary re-renders.

Example:

import { useCallback, useState } from 'react';

function Parent() {
  const [count, setCount] = useState(0);
  const handleClick = useCallback(() => {
    console.log('Button clicked!');
  }, []); // Empty dependency array means function is memoized
  
  return <Child onClick={handleClick} />;
}
2. What is `useMemo`, and when should you use it?

useMemo is a hook that memoizes the result of a computation, so it's only recalculated when dependencies change. Use it to optimize performance for expensive calculations.

Example:

import { useMemo, useState } from 'react';

function ExpensiveComponent({ numbers }) {
  const sum = useMemo(() => {
    return numbers.reduce((a, b) => a + b, 0);
  }, [numbers]);
  
  return <div>Sum: {sum}</div>;
}
3. How do you handle side effects in React?

Side effects (like data fetching, timers, or DOM updates) are handled using the useEffect hook in functional components or lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount) in class components.

Example with useEffect:

import { useEffect, useState } from 'react';

function DataFetcher() {
  const [data, setData] = useState(null);
  
  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(res => res.json())
      .then(setData);
      
    return () => console.log('Cleanup'); // Cleanup on unmount
  }, []);
  
  return <div>{data ? data.name : 'Loading...'}</div>;
}
4. What is a Pure Component in React?

A Pure Component is a class component that automatically implements shouldComponentUpdate with a shallow comparison of props and state to prevent unnecessary re-renders. Functional components can achieve this with React.memo.

Example:

class PureComp extends React.PureComponent {
  render() {
    return <div>{this.props.value}</div>;
  }
}
5. What is the difference between `useEffect` and `useLayoutEffect`?

Example:

import { useLayoutEffect } from 'react';

function LayoutEffectExample() {
  useLayoutEffect(() => {
    console.log('Runs before painting');
  }, []);
  
  return <div>Hello</div>;
}
6. How do you prevent a component from re-rendering unnecessarily?

To prevent unnecessary re-renders:

Example with React.memo:

const MyComponent = React.memo(({ value }) => {
  return <div>{value}</div>;
});
7. What is the `useRef` hook, and how is it used?

useRef creates a mutable object that persists across renders. It's commonly used to:

Example:

import { useRef } from 'react';

function InputFocus() {
  const inputRef = useRef(null);
  const focusInput = () => inputRef.current.focus();
  
  return (
    <div>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus</button>
    </div>
  );
}
8. How do you handle authentication in a React app?

Authentication can be handled by:

Example:

import { useContext } from 'react';
import { AuthContext } from './AuthContext';

function ProtectedRoute({ children }) {
  const { isAuthenticated } = useContext(AuthContext);
  return isAuthenticated ? children : <Redirect to="/login" />;
}
9. What is the purpose of `React.Fragment`?

React.Fragment lets you group multiple elements without adding extra DOM nodes (like a <div>). It's useful for cleaner HTML output.

Example:

function List() {
  return (
    <React.Fragment>
      <li>Item 1</li>
      <li>Item 2</li>
    </React.Fragment>
  );
}
10. What is lazy loading in React, and how do you implement it?

Lazy loading delays loading of components until they're needed, improving app performance. Use React.lazy and Suspense.

Example:

import { lazy, Suspense } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
}
11. What is the difference between `useState` and `useRef` for managing values?

Example:

function Example() {
  const [count, setCount] = useState(0); // Triggers re-render
  const refCount = useRef(0); // No re-render
  
  return (
    <div>
      <button onClick={() => setCount(count + 1)}>State: {count}</button>
      <button onClick={() => (refCount.current += 1)}>Ref: {refCount.current}</button>
    </div>
  );
}
12. How do you handle errors in async operations in React?

Use try-catch in async functions inside useEffect or other hooks, and maintain an error state to display error messages.

Example:

import { useState, useEffect } from 'react';

function DataFetcher() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    async function fetchData() {
      try {
        const res = await fetch('https://api.example.com/data');
        const result = await res.json();
        setData(result);
      } catch (err) {
        setError('Failed to fetch data');
      }
    }
    fetchData();
  }, []);
  
  return <div>{error ? error : data ? data.name : 'Loading...'}</div>;
}
13. What is the `key` prop, and what happens if you don't use it in a list?

The key prop uniquely identifies elements in a list, helping React efficiently update the DOM. Without a key, React may re-render the entire list, causing performance issues or incorrect UI updates.

Example:

const items = ['Apple', 'Banana'];

function List() {
  return (
    <ul>
      {items.map(item => (
        <li key={item}>{item}</li> // Use unique key
      ))}
    </ul>
  );
}
14. How do you manage global state in a React app?

Global state can be managed using:

Example with Context:

const GlobalContext = React.createContext();

function App() {
  const [state, setState] = useState({ theme: 'light' });
  
  return (
    <GlobalContext.Provider value={{ state, setState }}>
      <Child />
    </GlobalContext.Provider>
  );
}
15. What is the difference between `React.memo` and `useMemo`?

Example:

const MemoizedComponent = React.memo(({ value }) => <div>{value}</div>);

const expensiveValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
16. How do you test React components?

React components can be tested using libraries like:

Example:

import { render, screen } from '@testing-library/react';

test('renders button', () => {
  render(<Button label="Click me" />);
  expect(screen.getByText('Click me')).toBeInTheDocument();
});
17. What is the purpose of `React.StrictMode`?

React.StrictMode is a tool for highlighting potential problems in a React app during development. It:

Example:

function App() {
  return (
    <React.StrictMode>
      <MyComponent />
    </React.StrictMode>
  );
}
18. How do you handle routing in a single-page application (SPA)?

Use React Router to manage routing in an SPA. It allows navigation without full page reloads. Key components:

Example:

import { BrowserRouter, Route, Switch } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/home" component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </BrowserRouter>
  );
}
19. What are custom hooks, and how do you create one?

Custom hooks are reusable functions that encapsulate logic using React hooks. They start with "use" and can call other hooks.

Example:

import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  
  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(setData);
  }, [url]);
  
  return data;
}

function Component() {
  const data = useFetch('https://api.example.com/data');
  return <div>{data ? data.name : 'Loading...'}</div>;
}
20. How do you optimize a React app for SEO?

To make a React app SEO-friendly:

Example with react-helmet:

import { Helmet } from 'react-helmet';

function Page() {
  return (
    <div>
      <Helmet>
        <title>My Page Title</title>
        <meta name="description" content="This is my page" />
      </Helmet>
      <h1>Hello</h1>
    </div>
  );
}

🎯 Tips for Interview Success