25 Essential React Interview Questions & Answers

Study core concepts, performance, and best practices to ace your next React interview.

1. What are React Hooks and what problem do they solve?

React Hooks are functions that let you ‘hook into’ React state and lifecycle features from function components. They were introduced in React 16.8 to allow developers to write stateful logic without using classes, solving issues like confusing this binding, difficulty reusing stateful logic between components, and the complexity of lifecycle methods in classes.

2. Explain the Virtual DOM (VDOM) and Reconciliation process.

The Virtual DOM is a lightweight copy of the real DOM. When state changes, React updates the VDOM first. Reconciliation is the process where React’s Diffing Algorithm compares the new VDOM with the previous one. It calculates the minimum number of changes needed and batches them to update the real DOM efficiently, which is generally much faster than direct DOM manipulation.

3. Differentiate between Controlled and Uncontrolled Components.

In Controlled Components, form data (e.g., input values) is handled by the React component’s state. The state is the ‘single source of truth’ for the input value, updated via an onChange handler. In Uncontrolled Components, form data is handled by the DOM itself. You use a ref to access the value directly when needed (e.g., on form submission). Controlled components are preferred for immediate validation and dynamic input handling.

4. Describe the purpose of useEffect and its dependency array.

The useEffect Hook allows you to perform side effects (data fetching, subscriptions, manually changing the DOM, timers) in function components. The dependency array ([]) controls when the effect runs:
– Empty array ([]): Runs once after the initial render (like componentDidMount).
– No array: Runs after every render.
– Array with values ([a, b]): Runs on the initial render and whenever a or b change.

5. What is the difference between state and props?

Props (properties) are used to pass data from a parent component to a child component. They are read-only and immutable. State is a private object that is managed within a component (using useState). It holds data that may change over time and causes the component to re-render when updated.

6. What is prop drilling and how can you avoid it?

Prop drilling is the process of passing data (props) through several layers of intermediate components that don’t actually need the data, simply to get it to a deeply nested child component. It can be avoided using Context API (for application-wide state), or state management libraries like Redux/Zustand, or by using Component Composition (passing a component as a prop).

7. Explain the concept of Higher-Order Components (HOCs).

A Higher-Order Component (HOC) is an advanced React technique for reusing component logic. It is a function that takes a component as an argument and returns a new component with enhanced functionality (e.g., data fetching, authentication checks, logging). HOCs are slowly being replaced by custom Hooks.

8. When should you use useMemo and useCallback?

useMemo is used to memoize the result of an expensive calculation, preventing it from being re-calculated on every render unless its dependencies change. useCallback is used to memoize a function definition itself, which is crucial when passing callback functions to optimized child components to prevent unnecessary re-renders of the child.

9. What is Context API and when should you use it?

The Context API provides a way to share values (like user authentication status, themes, or locale data) between components without having to explicitly pass a prop through every level of the component tree (avoiding prop drilling). You should use it for data that is considered ‘global’ for a tree of React components.

10. Explain the importance of Keys when rendering lists.

Keys are necessary when rendering a list of elements. They give React a stable identity for each item in the list. This allows React to efficiently update, reorder, or delete items. Keys should be unique among siblings and should ideally be a stable identifier from the data (like a database ID), not the array index (which can change if the list is reordered).

11. What is React Router and how does it enable client-side routing?

React Router is a standard library used to define navigation and routing within a single-page application (SPA). It dynamically changes the rendered components based on the URL in the browser without requiring a full page refresh, simulating multi-page navigation on the client-side using the browser’s History API.

12. How do you handle side effects like data fetching in function components?

You primarily use the useEffect Hook for side effects. For data fetching, the logic is usually placed inside useEffect, and it’s essential to include an empty dependency array ([]) if you only want to fetch the data once on mount, or include relevant dependencies if the fetching logic depends on state or props.

13. Describe the four phases of a component’s lifecycle (Mounting, Updating, Unmounting).

1. Mounting: Component is being created and inserted into the DOM. (Hooks: useState initialization, useEffect with []). 2. Updating: Component re-renders due to changes in state or props. (Hooks: Component body runs, useEffect runs). 3. Unmounting: Component is removed from the DOM. (Hooks: Cleanup function returned by useEffect). 4. Error Handling: When an error occurs during rendering, in a lifecycle method, or in a constructor.

14. What is JSX and why is it used?

JSX (JavaScript XML) is a syntax extension for JavaScript recommended by React. It allows you to write HTML-like structures directly within your JavaScript code. It is not mandatory, but it simplifies component structure and is compiled (via Babel) into standard JavaScript function calls (React.createElement) that create React elements.

15. What is Server-Side Rendering (SSR) in React and its benefits?

Server-Side Rendering (SSR) is when a React application’s initial rendering is performed on the server, generating full HTML, which is then sent to the browser. Benefits include Improved SEO (search engines see fully rendered HTML) and Faster Time-to-Content (the user sees content sooner, improving perceived performance).

16. How do you optimize performance in a React application?

Performance can be optimized by: 1. Using React.memo (for functional components) or shouldComponentUpdate (for class components) to prevent unnecessary re-renders. 2. Using useMemo and useCallback to memoize expensive values and functions. 3. Lazy loading components using React.lazy and Suspense. 4. Virtualization for long lists. 5. Using Keys correctly in lists.

17. What are Fragments and why use them?

Fragments (<React.Fragment> or <>...</>) allow you to group a list of children without adding extra nodes to the DOM. Since React components must return a single element, fragments are used when you need multiple elements without wrapping them in an unnecessary <div>, improving DOM structure and performance.

18. What is React.memo?

React.memo is a Higher-Order Component (HOC) used to optimize functional components. If the component receives the same props as the previous render, React.memo will skip rendering the component and reuse the last rendered result, preventing unnecessary re-renders.

19. How does the useReducer Hook differ from useState?

useReducer is an alternative to useState for state management, particularly useful for handling complex state logic that involves multiple sub-values or when the next state depends on the previous one. It takes a reducer function (similar to Redux) and an initial state, and returns the current state and a dispatch function.

20. What is a React Portal?

A Portal provides a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. This is commonly used for modal dialogs, tooltips, or popovers, allowing them to escape the parent’s overflow or styling restrictions.

21. Code Evaluation: What is the output of this component and why?

The output will be ‘Count: 1’. This is because setCount(count + 1) and setCount(count + 1) are both executed within the same render cycle (the click handler). React batches state updates, so both calls see the same initial value of count (which is 0). The result is that 0 + 1 is applied twice, but since it’s the same update, it only increments once.

22. Code Evaluation: How would you fix the previous component to increment twice?

You must use the functional form of the state update (setCount(prevCount => prevCount + 1)). This functional form ensures that the update uses the latest available state value, bypassing the batching issue and correctly incrementing the count by two.

Code Example:

// Before:


const handleClick = () => {
setCount(count + 1); // 0 + 1 = 1
setCount(count + 1); // 0 + 1 = 1
};

// After (Corrected):
const handleClick = () => {
setCount(prevCount => prevCount + 1); // 0 -> 1
setCount(prevCount => prevCount + 1); // 1 -> 2
};

Evaluation: The functional update form (prevCount => ...) ensures sequential updates based on the correct previous state, resulting in ‘Count: 2’.

23. Code Evaluation: What is wrong with this useEffect dependency array?

The dependency array is missing myCount and myValue. According to the Rules of Hooks, any variable or function defined outside of the effect (and used inside the effect) must be included in the dependency array. If myCount changes, the effect will use a stale value of myCount from the initial render, causing a bug.

Code Example:

function MyComponent({ myValue }) {


const [myCount, setCount] = useState(0);

useEffect(() => {
console.log(myCount, myValue);
// Effect uses myCount and myValue but dependency array is empty
}, []);

// ...
}

Evaluation: The useEffect dependency array should be [myCount, myValue] to prevent stale closure issues and ensure the effect re-runs when those values change.

24. What are custom Hooks and provide an example use case.

A custom Hook is a JavaScript function whose name starts with ‘use’ (e.g., useFetch, useLocalStorage). It’s used to extract and share stateful logic between different components without relying on HOCs or render props. Example Use Case: A useLocalStorage Hook to abstract the logic for reading and writing state to the browser’s localStorage.

25. What is Strict Mode and what benefits does it provide?

Strict Mode is a tool for highlighting potential problems in an application. It does not render any visible UI but activates extra checks and warnings for its descendants. It helps in: 1. Detecting deprecated feature usage. 2. Highlighting potentially unsafe lifecycles in class components. 3. Warning about legacy string ref API usage. 4. Double-invoking effects/constructors to check for unintended side effects.


Posted

in

by

Tags:

Comments

Leave a Reply

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