Posted in

Top 30 React Interview Questions and Answers for All Levels

Prepare for your React developer interview with these 30 essential React interview questions covering basic, intermediate, and advanced topics. This guide is designed for freshers, candidates with 1-3 years of experience, and professionals with 3-6 years in React development. Each question includes clear, practical answers with code examples.

Basic React Interview Questions (1-10)

1. What is React and how does it work?

React is a JavaScript library for building user interfaces by creating reusable UI components. It works using a Virtual DOM – a lightweight copy of the real DOM that tracks changes efficiently through a reconciliation process, updating only the changed parts of the real DOM.[1]

2. What is JSX and how is it converted to JavaScript?

JSX is a syntax extension for JavaScript that looks like HTML, allowing developers to write UI components intuitively. It gets transpiled to regular JavaScript by tools like Babel before being executed by the browser.[1]

3. What is the difference between functional and class components in React?

Functional components are simple JavaScript functions that return JSX and are stateless by default. Class components extend React.Component, can maintain state using this.state, and support lifecycle methods.[1]

  • Functional: No lifecycle methods, uses hooks for state
  • Class: Has lifecycle methods, uses this.state/this.setState

4. What is the purpose of the render() method?

The render() method is required in class components and returns the JSX that describes the UI. React calls this method whenever it needs to re-render a component.[5]

5. What are props in React?

Props (properties) are read-only data passed from parent components to child components. They enable component reusability and communication between components.[1]

function Child({ name }) {
  return <p>Hello, {name}!</p>;
}
// Usage: <Child name="John" />

6. What is state in React?

State is a built-in object that stores dynamic data that changes over time within a component. When state changes, React automatically re-renders the component.[1]

7. What is the useState hook?

useState is a React hook that adds state to functional components. It returns an array with the current state value and a setter function.[5]

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}

8. What are React lifecycle methods?

Lifecycle methods are special methods in class components that run at specific points during a component’s lifecycle: mounting, updating, and unmounting.[5]

9. What is componentDidMount()?

componentDidMount() runs after the component is rendered to the DOM for the first time. It’s commonly used for API calls and DOM manipulations.[5]

10. What is the Virtual DOM?

Virtual DOM is a lightweight JavaScript object representation of the real DOM. React creates a new Virtual DOM tree on each update and uses a diffing algorithm to efficiently update only changed parts.[1][3]

Intermediate React Interview Questions (11-20)

11. What is the difference between useState and useReducer?

useState is for simple state management. useReducer is for complex state logic with multiple sub-values or when next state depends on previous state.[5]

12. What is useEffect hook?

useEffect handles side effects in functional components like data fetching, subscriptions, or DOM manipulations. It runs after render and can simulate lifecycle methods.[5]

useEffect(() => {
  // Fetch data
  fetchData();
  
  // Cleanup
  return () => cleanup();
}, [dependency]);

13. How do you prevent unnecessary re-renders in React?

Use React.memo for memoizing components, useMemo for expensive calculations, and useCallback for functions passed as props to prevent child re-renders.[1]

14. What is React Context and when should you use it?

React Context provides a way to pass data through the component tree without prop drilling. Use it for global data like themes, authentication, or user preferences.[3]

15. What is the key prop and why is it important?

The key prop helps React identify which items have changed, been added, or removed in lists. Keys should be stable, unique identifiers, not array indices.[1]

16. How do you handle forms in React?

React uses controlled components where form data is handled by React state. Input values are bound to state and updated via onChange handlers.[4]

function LoginForm() {
  const [formData, setFormData] = useState({ email: '', password: '' });
  
  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };
  
  return <input name="email" value={formData.email} onChange={handleChange} />;
}

17. What is conditional rendering in React?

Conditional rendering displays different JSX based on conditions using if statements, ternary operators, or logical && operator.[1]

{isLoggedIn ? <UserDashboard /> : <Login />}
{data && <List data={data} />}

18. What are React fragments?

React Fragments (<></> or <React.Fragment>) allow grouping multiple elements without adding extra DOM nodes.[1]

19. How do you fetch data in a React component?

Use useEffect with async/await inside functional components. Always include proper error handling and loading states.[3]

useEffect(() => {
  const fetchData = async () => {
    try {
      const response = await fetch('/api/data');
      const data = await response.json();
      setData(data);
    } catch (error) {
      setError(error);
    }
  };
  fetchData();
}, []);

20. What is prop drilling and how to avoid it?

Prop drilling occurs when props are passed through multiple component levels. Use React Context or component composition to avoid it.[3]

Advanced React Interview Questions (21-30)

21. What is React.memo and when to use it?

React.memo is a higher-order component that memoizes functional components, preventing re-renders when props haven’t changed. Use for expensive components.[1]

22. Explain useCallback vs useMemo

useCallback memoizes functions to prevent unnecessary re-creations. useMemo memoizes expensive calculations. Both optimize performance.[1]

23. What is a Higher-Order Component (HOC)?

An HOC is a function that takes a component and returns a new component with enhanced functionality. Common pattern for cross-cutting concerns like authentication.[3]

24. What is custom hook?

Custom hooks are JavaScript functions starting with “use” that use other hooks. They promote code reusability and logic extraction.[4]

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

25. How does React batch state updates?

React automatically batches multiple setState calls in event handlers and timeouts to improve performance, executing them as a single re-render.[1]

26. What is StrictMode in React?

StrictMode is a development tool that highlights potential problems by running certain functions twice and enabling extra checks.[5]

27. Explain React’s reconciliation process

Reconciliation compares the new Virtual DOM with the previous one using a diffing algorithm. It performs tree traversal and only updates changed elements.[3]

28. What are error boundaries?

Error boundaries are class components that catch JavaScript errors in child component trees using static getDerivedStateFromError() and componentDidCatch().[1]

29. How do you optimize large lists in React?

Use virtualization libraries like react-window or react-virtualized to render only visible items, dramatically improving performance for large datasets.[1]

30. What is code splitting in React?

Code splitting loads JavaScript bundles lazily using React.lazy() and Suspense. It improves initial load time by loading components only when needed.[1]

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *