React Interview Questions
85 questions with detailed answers
Question:
What are React components and what types exist?
Answer:
React components are reusable pieces of UI. Types include: Functional Components (using functions), Class Components (using ES6 classes), Pure Components (optimized class components), and Higher-Order Components (HOCs).
Question:
What is the difference between state and props in React?
Answer:
Props are read-only data passed from parent to child components. State is mutable data managed within a component.
// Props example
function Child({ name }) {
return <p>Hello {name}</p>;
}
// State example
function Parent() {
const [count, setCount] = useState(0);
return <Child name="React" />;
}Question:
How do you create a functional component in React?
Answer:
A functional component is created using a JavaScript function that returns JSX. Example: function MyComponent() { return <div>Hello World</div>; } or const MyComponent = () => <div>Hello World</div>;
Question:
What is the useState hook and how is it used?
Answer:
useState is a React hook that allows functional components to have state. It returns an array with the current state value and a function to update it.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}Question:
What is event handling in React?
Answer:
Event handling in React uses SyntheticEvents, which are React's wrapper around native events. Events use camelCase naming and functions are passed as event handlers.
function Button() {
const handleClick = (e) => {
e.preventDefault();
console.log("Button clicked!");
};
return <button onClick={handleClick}>Click me</button>;
}Question:
What is conditional rendering in React?
Answer:
Conditional rendering allows showing different UI based on certain conditions. It can be done using if statements, ternary operators, logical AND (&&) operator, or switch statements within JSX.
Question:
How do you render lists in React?
Answer:
Lists are rendered using the map() method to iterate over arrays and return JSX elements. Each list item should have a unique "key" prop.
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}Question:
What is React and what are its main features?
Answer:
React is a JavaScript library for building user interfaces. Main features include: Virtual DOM, Component-based architecture, JSX syntax, One-way data binding, Declarative programming style, and Strong ecosystem.
Question:
What is JSX and why is it used in React?
Answer:
JSX (JavaScript XML) is a syntax extension for JavaScript that allows writing HTML-like code in JavaScript. It makes React components more readable and allows embedding JavaScript expressions within HTML-like syntax.
Question:
What is the Virtual DOM and how does it work?
Answer:
Virtual DOM is a JavaScript representation of the real DOM. React creates a virtual copy of the DOM in memory, compares it with the previous version when changes occur, and updates only the changed parts in the real DOM, making it more efficient.
Question:
What are React components and what types exist?
Answer:
React components are reusable pieces of UI. Types include: Functional Components (using functions), Class Components (using ES6 classes), Pure Components (optimized class components), and Higher-Order Components (HOCs).
Question:
What is the difference between state and props in React?
Answer:
Props are read-only data passed from parent to child components. State is mutable data managed within a component. Props are external inputs, while state is internal component data that can change over time.
Question:
How do you create a functional component in React?
Answer:
A functional component is created using a JavaScript function that returns JSX. Example: function MyComponent() { return <div>Hello World</div>; } or const MyComponent = () => <div>Hello World</div>;
Question:
What is the useState hook and how is it used?
Answer:
useState is a React hook that allows functional components to have state. It returns an array with the current state value and a function to update it. Example: const [count, setCount] = useState(0);
Question:
What is event handling in React?
Answer:
Event handling in React uses SyntheticEvents, which are React's wrapper around native events. Events are handled using camelCase naming (onClick, onChange) and functions are passed as event handlers.
Question:
What is conditional rendering in React?
Answer:
Conditional rendering allows showing different UI based on certain conditions. It can be done using if statements, ternary operators, logical AND (&&) operator, or switch statements within JSX.
Question:
How do you render lists in React?
Answer:
Lists are rendered using the map() method to iterate over arrays and return JSX elements. Each list item should have a unique "key" prop for React to track changes efficiently.
Question:
What is React and what are its main features?
Answer:
React is a JavaScript library for building user interfaces. Main features include:
- Virtual DOM: Efficient updates and rendering
- Component-based: Reusable UI components
- JSX: HTML-like syntax in JavaScript
- One-way data binding: Predictable data flow
// Simple React component
function Welcome() {
return <h1>Hello, React!</h1>;
}Question:
What is JSX and why is it used in React?
Answer:
JSX (JavaScript XML) is a syntax extension for JavaScript that allows writing HTML-like code in JavaScript. It makes React components more readable and allows embedding JavaScript expressions.
// JSX Example
const element = <h1>Hello, {name}!</h1>;
// Compiles to:
const element = React.createElement("h1", null, "Hello, ", name, "!");Question:
What is the Virtual DOM and how does it work?
Answer:
Virtual DOM is a JavaScript representation of the real DOM. React creates a virtual copy, compares it with the previous version when changes occur, and updates only the changed parts.
// Virtual DOM concept
const virtualElement = {
type: "div",
props: { className: "container" },
children: ["Hello World"]
};Question:
What is the useEffect hook and when is it used?
Answer:
useEffect is used for side effects in functional components like API calls, subscriptions, or DOM manipulation. It runs after render and can be controlled with dependency arrays.
import { useEffect, useState } from "react";
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]); // Runs when userId changes
return <div>{user?.name}</div>;
}Question:
What are React keys and why are they important?
Answer:
Keys are unique identifiers for list elements that help React identify which items have changed, been added, or removed. They improve performance and prevent rendering issues.
// Good: Using unique keys
{items.map(item => (
<Item key={item.id} data={item} />
))}
// Bad: Using array index
{items.map((item, index) => (
<Item key={index} data={item} />
))}Question:
What is component lifecycle in React class components?
Answer:
Component lifecycle includes mounting (componentDidMount), updating (componentDidUpdate), and unmounting (componentWillUnmount) phases. Each phase has specific methods for handling different operations.
Question:
What is prop drilling and how can it be avoided?
Answer:
Prop drilling is passing props through multiple component levels. It can be avoided using Context API, Redux, component composition, or custom hooks to manage state more efficiently.
Question:
What is the Context API and when should you use it?
Answer:
Context API provides a way to share data across components without prop drilling. Use it for global data like themes, user authentication, or language preferences.
// Create context
const ThemeContext = createContext();
// Provider
function App() {
return (
<ThemeContext.Provider value="dark">
<Header />
</ThemeContext.Provider>
);
}
// Consumer
function Header() {
const theme = useContext(ThemeContext);
return <div className={theme}>Header</div>;
}Question:
What are controlled and uncontrolled components?
Answer:
Controlled components have their form data handled by React state. Uncontrolled components store form data in the DOM itself.
// Controlled component
function ControlledInput() {
const [value, setValue] = useState("");
return (
<input
value={value}
onChange={e => setValue(e.target.value)}
/>
);
}
// Uncontrolled component
function UncontrolledInput() {
const inputRef = useRef();
return <input ref={inputRef} />;
}Question:
What is React Router and how does it work?
Answer:
React Router is a library for handling navigation in React applications. It enables single-page applications with multiple views using components like BrowserRouter, Route, Link, and Switch.
Question:
What are React fragments and why use them?
Answer:
React fragments (<React.Fragment> or <></>) allow grouping multiple elements without adding extra DOM nodes. They help maintain clean HTML structure and avoid unnecessary wrapper divs.
Question:
What is the difference between createElement and JSX?
Answer:
JSX is syntactic sugar for React.createElement(). JSX is more readable and familiar to HTML, while createElement is the underlying function that creates React elements programmatically.
Question:
How do you handle forms in React?
Answer:
Forms are handled using controlled components with state, event handlers for input changes, and form submission. Use useState for form data and onChange events to update state values.
Question:
What is the useCallback hook and when to use it?
Answer:
useCallback memoizes functions to prevent unnecessary re-renders. Use it when passing callbacks to child components that depend on specific values.
function Parent({ items }) {
const [count, setCount] = useState(0);
const handleClick = useCallback((id) => {
// Function only recreated if count changes
console.log(`Clicked ${id}, count: ${count}`);
}, [count]);
return (
<div>
{items.map(item => (
<Child key={item.id} onClick={handleClick} />
))}
</div>
);
}Question:
What is the useMemo hook and its purpose?
Answer:
useMemo memoizes expensive calculations to avoid recalculating on every render. It returns a memoized value that only recalculates when dependencies change.
function ExpensiveComponent({ items, filter }) {
const filteredItems = useMemo(() => {
return items.filter(item =>
item.name.includes(filter)
);
}, [items, filter]);
return (
<ul>
{filteredItems.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}Question:
What are Higher-Order Components (HOCs)?
Answer:
HOCs are functions that take a component and return a new component with additional props or functionality. They enable code reuse and cross-cutting concerns like authentication or logging.
Question:
What are React Hooks?
Answer:
React Hooks are functions that let you use state and other React features in functional components. They were introduced in React 16.8.\n\nCommon hooks:\n- useState: Manages component state\n- useEffect: Handles side effects\n- useContext: Consumes context\n- useReducer: Complex state management\n\nExample:\nfunction Counter() {\n const [count, setCount] = useState(0);\n \n useEffect(() => {\n document.title = `Count: ${count}`;\n }, [count]);\n \n return (\n \n );\n}
Question:
What is React.memo and when should you use it?
Answer:
React.memo is a higher-order component that memoizes functional components. It prevents re-renders when props haven't changed, similar to PureComponent for class components.
Question:
What is the Virtual DOM?
Answer:
The Virtual DOM is a JavaScript representation of the actual DOM. React creates and maintains a virtual representation of the UI in memory.\n\nHow it works:\n1. State changes trigger re-render\n2. New virtual DOM tree is created\n3. React compares (diffs) old and new trees\n4. Only necessary changes are applied to real DOM\n\nBenefits:\n- Better performance\n- Predictable updates\n- Cross-browser compatibility\n- Enables features like server-side rendering\n\nThe diffing algorithm makes updates efficient by minimizing DOM manipulations.
Question:
What are custom hooks and how do you create them?
Answer:
Custom hooks are JavaScript functions that start with "use" and can call other hooks. They allow sharing stateful logic between components without changing component hierarchy.
Question:
What is prop drilling and how to avoid it?
Answer:
Prop drilling is passing props through multiple component layers to reach a deeply nested component that needs the data.\n\nProblem:\nApp -> Header -> Navigation -> UserMenu (needs user data)\n\nSolutions:\n1. Context API:\nconst UserContext = createContext();\n\n2. State management libraries (Redux, Zustand)\n\n3. Component composition:\nfunction App() {\n return (\n
Question:
What is useEffect and its cleanup?
Answer:
useEffect handles side effects in functional components. It runs after render and can optionally clean up.\n\nBasic usage:\nuseEffect(() => {\n // Side effect\n document.title = "New Title";\n}, [dependency]); // Dependency array\n\nWith cleanup:\nuseEffect(() => {\n const timer = setInterval(() => {\n console.log("Timer tick");\n }, 1000);\n \n // Cleanup function\n return () => {\n clearInterval(timer);\n };\n}, []);\n\nDependency array:\n- [] = run once (componentDidMount)\n- [value] = run when value changes\n- no array = run on every render
Question:
What is the difference between controlled and uncontrolled components?
Answer:
Controlled components: Form data handled by React state\nUncontrolled components: Form data handled by DOM\n\nControlled example:\nfunction ControlledInput() {\n const [value, setValue] = useState("");\n \n return (\n setValue(e.target.value)} \n />\n );\n}\n\nUncontrolled example:\nfunction UncontrolledInput() {\n const inputRef = useRef();\n \n const handleSubmit = () => {\n console.log(inputRef.current.value);\n };\n \n return ;\n}\n\nControlled components are preferred for validation and dynamic behavior.
Question:
What is the useEffect hook and when is it used?
Answer:
useEffect is used for side effects in functional components like API calls, subscriptions, or DOM manipulation. It runs after render and can be controlled with dependency arrays to optimize performance.
Question:
What are React keys and why are they important?
Answer:
Keys are unique identifiers for list elements that help React identify which items have changed, been added, or removed. They improve performance and prevent rendering issues in dynamic lists.
Question:
What is component lifecycle in React class components?
Answer:
Component lifecycle includes mounting (componentDidMount), updating (componentDidUpdate), and unmounting (componentWillUnmount) phases. Each phase has specific methods for handling different operations.
Question:
What is prop drilling and how can it be avoided?
Answer:
Prop drilling is passing props through multiple component levels. It can be avoided using Context API, Redux, component composition, or custom hooks to manage state more efficiently.
Question:
What is the Context API and when should you use it?
Answer:
Context API provides a way to share data across components without prop drilling. Use it for global data like themes, user authentication, or language preferences that many components need.
Question:
What are controlled and uncontrolled components?
Answer:
Controlled components have their form data handled by React state. Uncontrolled components store form data in the DOM itself. Controlled components provide better data flow control and validation.
Question:
What is React Router and how does it work?
Answer:
React Router is a library for handling navigation in React applications. It enables single-page applications with multiple views using components like BrowserRouter, Route, Link, and Switch.
Question:
What are React fragments and why use them?
Answer:
React fragments (<React.Fragment> or <></>) allow grouping multiple elements without adding extra DOM nodes. They help maintain clean HTML structure and avoid unnecessary wrapper divs.
Question:
What is the difference between createElement and JSX?
Answer:
JSX is syntactic sugar for React.createElement(). JSX is more readable and familiar to HTML, while createElement is the underlying function that creates React elements programmatically.
Question:
How do you handle forms in React?
Answer:
Forms are handled using controlled components with state, event handlers for input changes, and form submission. Use useState for form data and onChange events to update state values.
Question:
What is the useCallback hook and when to use it?
Answer:
useCallback memoizes functions to prevent unnecessary re-renders. Use it when passing callbacks to child components that depend on specific values, helping optimize performance in React applications.
Question:
What is the useMemo hook and its purpose?
Answer:
useMemo memoizes expensive calculations to avoid recalculating on every render. It returns a memoized value that only recalculates when dependencies change, improving performance.
Question:
What are Higher-Order Components (HOCs)?
Answer:
HOCs are functions that take a component and return a new component with additional props or functionality. They enable code reuse and cross-cutting concerns like authentication or logging.
Question:
What is React.memo and when should you use it?
Answer:
React.memo is a higher-order component that memoizes functional components. It prevents re-renders when props haven't changed, similar to PureComponent for class components.
Question:
What are custom hooks and how do you create them?
Answer:
Custom hooks are JavaScript functions that start with "use" and can call other hooks. They allow sharing stateful logic between components without changing component hierarchy.
Question:
How would you implement a custom hook for API data fetching?
Answer:
Create a custom hook using useState for data/loading/error states and useEffect for the API call. Include cleanup for cancelled requests and return the states and refetch function for component use.
Question:
What are the best practices for React component architecture?
Answer:
Keep components small and focused, use composition over inheritance, separate container and presentational components, implement proper prop validation, and follow consistent naming conventions.
Question:
What is the difference between React and other frameworks like Vue or Angular?
Answer:
React is a library focused on UI with a component-based architecture and virtual DOM. Vue offers template syntax and two-way binding. Angular is a full framework with TypeScript, dependency injection, and comprehensive tooling.
Question:
What is React Suspense and how does it work?
Answer:
React Suspense allows components to "wait" for something before rendering, typically for code splitting or data fetching. It shows fallback UI while waiting.
import { Suspense, lazy } from "react";
const LazyComponent = lazy(() => import("./LazyComponent"));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}Question:
Explain React's reconciliation algorithm and fiber architecture.
Answer:
Reconciliation is React's diffing algorithm that compares virtual DOM trees. Fiber is the new reconciliation engine that enables incremental rendering, prioritization, and better performance through time-slicing.
Question:
What are render props and how do they work?
Answer:
Render props is a pattern where a component receives a function as a prop that returns JSX. It enables sharing code between components using a prop whose value is a function.
Question:
What is code splitting in React and how to implement it?
Answer:
Code splitting breaks the bundle into smaller chunks loaded on demand. Implement using React.lazy() for component-level splitting or dynamic imports for route-based splitting with Suspense.
Question:
What is the useReducer hook and when to use it over useState?
Answer:
useReducer manages complex state logic with multiple sub-values or when next state depends on previous state. Use it for complex state transitions.
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({type: "increment"})}>
+
</button>
</div>
);
}Question:
What are React portals and their use cases?
Answer:
Portals render children into a DOM node outside the parent component hierarchy. Use cases include modals, tooltips, dropdowns.
import { createPortal } from "react-dom";
function Modal({ children, isOpen }) {
if (!isOpen) return null;
return createPortal(
<div className="modal-overlay">
<div className="modal">
{children}
</div>
</div>,
document.getElementById("modal-root")
);
}Question:
What is React Server Components and their benefits?
Answer:
Server Components render on the server and send HTML to the client. Benefits include reduced bundle size, better performance, direct database access, and improved SEO while maintaining interactivity.
Question:
Explain React's concurrent features and time slicing.
Answer:
Concurrent React allows interrupting rendering to handle high-priority updates. Time slicing breaks rendering work into chunks, enabling React to pause and resume work, keeping the UI responsive.
Question:
What is the useImperativeHandle hook and its use cases?
Answer:
useImperativeHandle customizes the instance value exposed when using ref with forwardRef. Use it to expose specific methods or properties from child components to parent components.
Question:
What are React error boundaries and how to implement them?
Answer:
Error boundaries catch JavaScript errors in component trees and display fallback UI. Implement using class components with componentDidCatch() and getDerivedStateFromError().
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log("Error:", error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}Question:
What is React.StrictMode and its purpose?
Answer:
StrictMode is a development tool that highlights potential problems by intentionally double-invoking functions, detecting unsafe lifecycles, warning about deprecated APIs, and ensuring side-effect free rendering.
Question:
Explain React's batching mechanism and automatic batching.
Answer:
Batching groups multiple state updates into a single re-render for performance. React 18 introduced automatic batching for all updates, including promises, timeouts, and native event handlers.
Question:
What is the useLayoutEffect hook and how does it differ from useEffect?
Answer:
useLayoutEffect runs synchronously after DOM mutations but before browser paint. Use it for DOM measurements or synchronous DOM updates. useEffect runs asynchronously after paint.
Question:
What are React DevTools and their advanced features?
Answer:
React DevTools provide component inspection, profiling, and debugging. Advanced features include component profiling, interaction tracking, commit analysis, and performance bottleneck identification.
Question:
What is React's new JSX Transform and its benefits?
Answer:
New JSX Transform automatically imports React functions, eliminating the need to import React in every file. Benefits include smaller bundle size, better tree-shaking, and simplified imports.
Question:
Explain React's scheduling and priority system.
Answer:
React uses a priority-based scheduling system where updates are categorized by urgency. High-priority updates (user interactions) interrupt low-priority ones (data fetching) to maintain responsiveness.
Question:
What is React's startTransition API and its use cases?
Answer:
startTransition marks updates as non-urgent transitions, allowing React to interrupt them for more urgent updates. Use for expensive operations like filtering large lists or navigation.
Question:
What are React's experimental features and how to use them?
Answer:
Experimental features include Concurrent Mode, Server Components, and Selective Hydration. Enable them through feature flags or experimental builds, but avoid in production due to potential API changes.
Question:
What is React's useDeferredValue hook and its purpose?
Answer:
useDeferredValue defers updating a value until more urgent updates finish. It helps keep the UI responsive during expensive operations by showing stale values while new ones are being computed.
Question:
Explain React's hydration process and selective hydration.
Answer:
Hydration attaches event listeners to server-rendered HTML. Selective hydration allows prioritizing which components to hydrate first based on user interactions, improving perceived performance.
Question:
What are React's performance optimization techniques?
Answer:
Techniques include memoization (React.memo, useMemo, useCallback), code splitting, lazy loading, virtualization for large lists, avoiding inline objects/functions, and proper key usage.
Question:
What is React's useId hook and its use cases?
Answer:
useId generates unique IDs for accessibility attributes and form elements. It ensures consistent IDs between server and client rendering, preventing hydration mismatches in SSR applications.
Question:
Explain React's automatic batching and flushSync API.
Answer:
Automatic batching groups all state updates for better performance. flushSync forces synchronous updates when needed, bypassing batching for cases requiring immediate DOM updates.
Question:
What are React's testing strategies and best practices?
Answer:
Use React Testing Library for user-centric tests, Jest for unit tests, and tools like Cypress for E2E testing. Focus on testing behavior over implementation details and use proper test isolation.
Question:
What is React's useSyncExternalStore hook and its purpose?
Answer:
useSyncExternalStore subscribes to external data sources safely in concurrent React. It handles tearing issues and ensures consistent reads from external stores like Redux or browser APIs.
Question:
How do you optimize React application performance?
Answer:
Use React.memo for component memoization, implement code splitting, optimize bundle size, use proper keys in lists, avoid inline functions in render, and implement virtualization for large datasets.
Question:
How do you handle state management in large React applications?
Answer:
Use Context API for simple global state, Redux/Zustand for complex state management, React Query for server state, and local state for component-specific data. Choose based on complexity and requirements.