Top 50 Basic React interview Questions with Answers
1. What is React.js?
React.js is a JavaScript library for building user interfaces. It allows developers to create reusable UI components and manage their state efficiently in single-page applications.
2. What are the main features of React.js?
- Virtual DOM for performance optimization.
- Component-based architecture for reusable UI elements.
- Declarative programming for easier UI updates.
- Support for hooks for state and lifecycle management.
3. What is the virtual DOM? How does it work in React?
The virtual DOM is a lightweight copy of the real DOM. React uses it to compute the minimal number of changes needed and updates the actual DOM efficiently.
4. What is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code in your React components.
5. Explain the difference between functional and class components.
- Class components: Use ES6 classes, support lifecycle methods, and require
this
. - Functional components: Use functions, are simpler, and rely on hooks for state and lifecycle.
6. What is the purpose of render() in React?
The render()
method outputs the React element structure (UI) to the virtual DOM.
7. What are props in React?
Props (short for properties) are inputs passed from a parent component to a child component, making it dynamic and reusable.
8. What is state in React? How is it different from props?
- State: Internal to a component and managed within it.
- Props: External, passed down from parent to child components.
9. What are React lifecycle methods?
These methods manage a component’s lifecycle:
- Mounting:
componentDidMount
- Updating:
componentDidUpdate
- Unmounting:
componentWillUnmount
10. Explain the difference between componentDidMount and componentDidUpdate.
componentDidMount
: Runs after the component is mounted, ideal for API calls.componentDidUpdate
: Runs after every update, used for tasks like updating the DOM.
11. What is the purpose of shouldComponentUpdate?
It optimizes rendering by allowing you to prevent unnecessary re-renders based on conditional logic.
12. What is the use of keys in React lists?
Keys identify list items uniquely to help React efficiently update or reorder elements.
13. What are fragments in React?
Fragments allow grouping of child elements without adding extra nodes to the DOM.
14. What is a higher-order component (HOC)?
An HOC is a function that takes a component and returns an enhanced component, useful for reusing logic.
15. What is the purpose of refs in React?
Refs allow direct access to a DOM element or a React element instance.
16. What is the difference between controlled and uncontrolled components?
- Controlled: Form data is handled by React state.
- Uncontrolled: Form data is handled by the DOM directly.
17. What are portals in React?
Portals render children components outside the parent DOM hierarchy, useful for modals.
18. What is prop drilling in React, and how can it be avoided?
Prop drilling occurs when props are passed through multiple components. It can be avoided using Context API or state management libraries.
19. What is the significance of defaultProps?
It sets default values for props if none are provided.
20. How do you handle events in React?
React uses synthetic events, which wrap native events to provide consistent behavior across browsers. Example:
<button onClick={handleClick}>Click Me</button>
21. What is the difference between synthetic events in React and native DOM events?
Synthetic events are cross-browser wrappers around native events, ensuring consistency.
22. What are hooks in React?
Hooks are functions that let you use state and lifecycle features in functional components. Examples include useState
, useEffect
, and useContext
.
23. Explain useState and useEffect hooks with examples.
const [count, setCount] = useState(0);
useEffect(() => {
fetchData();
}, []);
24. What is the purpose of useRef hook?useRef
provides a mutable reference to a DOM element or variable that persists across renders.
25. What is React Context API?
A way to manage global state and avoid prop drilling by sharing data across components.
26. How is the Context API different from Redux?
Context API is simpler and built-in, suitable for small applications. Redux offers more powerful features like middleware and time-travel debugging for larger applications.
27. What is the purpose of React.memo()?React.memo()
prevents unnecessary re-renders by memoizing the rendered output of functional components.
28. What is the difference between useCallback and useMemo?
useCallback
: Memoizes a function.useMemo
: Memoizes a value or computation result.
29. How can you conditionally render elements in React?
Using logical operators or ternary expressions:
{isLoggedIn ? <Dashboard /> : <Login />}
30. What is lazy loading in React?
Lazy loading delays loading components until they are needed, improving performance.
31. What is React Suspense?
Suspense handles lazy loading and displays fallback content while components are loading.
32. What is the purpose of Error Boundaries in React?
Error boundaries catch JavaScript errors in child components and provide a fallback UI.
33. What is the use of strict mode in React?
Strict mode highlights potential issues in your application during development.
34. How do you optimize React applications?
- Use React.memo, lazy loading, and code splitting.
- Optimize re-renders with proper state management.
- Use production builds.
35. What is reconciliation in React?
Reconciliation is React’s process of comparing the new virtual DOM with the previous one to update only the necessary parts of the real DOM.
36. What is the difference between mounting, updating, and unmounting?
- Mounting: Adding elements to the DOM.
- Updating: Updating the DOM in response to state or prop changes.
- Unmounting: Removing elements from the DOM.
37. How do you implement routing in React?
Use react-router-dom
:
<Routes>
<Route path="/" element={<Home />} />
</Routes>
38. What are the differences between BrowserRouter and HashRouter?
- BrowserRouter: Uses clean URLs and the HTML5 history API.
- HashRouter: Uses the URL hash (#) for routing, ideal for legacy support.
39. How do you create forms in React?
Use controlled or uncontrolled components to handle form data.
40. What are synthetic events in React?
Synthetic events are React’s cross-browser wrappers for native events.
41. What is the use of useReducer hook?useReducer
manages complex state logic:
const [state, dispatch] = useReducer(reducer, initialState);
42. What is the difference between forEach and map in React?
forEach
: Iterates over elements without returning a new array.map
: Returns a new array by transforming elements.
43. How can you pass data between parent and child components in React?
Pass data as props from parent to child.
44. What are default exports and named exports in React?
- Default exports: Export one item per module.
- Named exports: Export multiple items.
45. What is the significance of the React key attribute?
Keys help React identify and manage elements efficiently during updates.
46. What is the difference between stateful and stateless components?
- Stateful: Components with internal state.
- Stateless: Components without internal state.
47. How do you handle errors in React?
Use Error Boundaries or try-catch in event handlers.
48. What is the difference between React and React Native?
- React is for web applications.
- React Native is for mobile app development.
49. How do you update state in React?
Use setState
in class components or useState
in functional components.
50. What is the use of PropTypes in React?
PropTypes validate props at runtime to ensure correct data types.
Top 50 Advance React interview Questions with Answers
1. What is the difference between React’s Context API and Redux?
- Context API: Used for passing data deeply without prop drilling, suitable for smaller-scale state management.
- Redux: A robust state management library for handling global state, supporting middleware, and features like time-travel debugging.
2. What are React Hooks? Name some commonly used hooks.
Hooks are functions that allow you to use React state and lifecycle methods in functional components. Common hooks:
useState
: Manage state.useEffect
: Handle side effects.useContext
: Access Context API.useReducer
: Manage complex state.useRef
: Access or persist DOM elements.
3. Explain how React’s reconciliation process works.
React compares the new virtual DOM tree with the old one (diffing) and calculates the minimal set of changes needed to update the real DOM efficiently.
4. What are lazy loading and code splitting?
- Lazy loading: Delays the loading of non-critical components until needed.
- Code splitting: Divides code into chunks to load only what is required.
Example withReact.lazy
andSuspense
const LazyComponent = React.lazy(() => import('./LazyComponent'));
5. How do you optimize performance in React applications?
- Use React.memo to prevent unnecessary re-renders.
- Split components with
React.lazy
. - Optimize state management (minimize re-renders).
- Use production builds.
- Avoid inline functions and styles.
6. What is the purpose of React.memo()?React.memo
is a higher-order component that prevents re-rendering of functional components unless their props change.
7. What is the use of useMemo and useCallback hooks?
useMemo
: Memoizes a computed value to avoid recalculations.useCallback
: Memoizes a function to prevent unnecessary re-creation.
const memoizedValue = useMemo(() => computeValue(data), [data]);
8. How do you implement server-side rendering (SSR) with React?
Use frameworks like Next.js for SSR. Key benefits include improved SEO and faster initial load times.
9. What is hydration in React?
Hydration is React’s process of attaching event listeners to pre-rendered HTML generated on the server.
10. What are higher-order components (HOCs)?
HOCs are functions that take a component and return an enhanced component. Common use cases include reusing logic, adding authentication, and managing permissions.
11. What is the difference between useEffect and useLayoutEffect?
useEffect
: Runs after the render phase.useLayoutEffect
: Runs synchronously after all DOM mutations, making it suitable for measurements and DOM manipulations.
12. What is the purpose of Error Boundaries?
Error Boundaries catch JavaScript errors in child components and render a fallback UI instead of crashing the app.
13. How do you manage side effects in React applications?
Use the useEffect
hook for tasks like API calls, subscriptions, and manual DOM updates.
14. What are controlled and uncontrolled components? Which one should you use?
- Controlled components: React controls the form data. Recommended for predictable state management.
- Uncontrolled components: The DOM handles form data. Useful for simple use cases.
15. How can you implement infinite scrolling in React?
Use an IntersectionObserver
or a scroll event to detect when the user reaches the bottom of a list and load more data.
16. What is prop drilling, and how can it be avoided?
Prop drilling occurs when data is passed through multiple components unnecessarily. Avoid it using Context API or state management libraries like Redux.
17. How do you handle authentication in React applications?
Use Context API, Redux, or third-party libraries like Firebase for managing authentication state. Protect routes using HOCs or custom hooks.
18. What are portals in React? How are they useful?
Portals render child components outside the parent DOM hierarchy. They are useful for modals, tooltips, and pop-ups.
19. Explain React’s batching mechanism.
React batches multiple state updates into a single render cycle for performance optimization.
20. What is the difference between synchronous and asynchronous state updates in React?
State updates in React are asynchronous for performance reasons. Updates are batched and applied after the component renders.
21. What are React fibers?
React Fiber is the new reconciliation algorithm in React, designed to enable rendering tasks to be split into small units and paused/resumed.
22. What is React’s Suspense API?
Suspense allows you to show a fallback UI while awaiting lazy-loaded components or asynchronous operations.
23. How do you handle complex state in React applications?
Use the useReducer
hook for complex state logic or state management libraries like Redux or MobX.
24. What is the use of React’s Context API?
Context API allows you to share state globally without prop drilling.
25. How do you handle performance bottlenecks in React?
- Profile components with React Developer Tools.
- Memoize functions and values.
- Avoid unnecessary re-renders with keys and shouldComponentUpdate.
- Optimize component structure and state hierarchy.
26. What is the difference between Redux and MobX?
- Redux: Centralized store, predictable state management, uses reducers.
- MobX: Decentralized stores, reactive programming, and easier learning curve.
27. What are React refs, and why are they used?
Refs are used to directly access or manipulate DOM elements or persist a value across renders.
28. What is state lifting in React?
State lifting involves moving state to a common parent component to share it between sibling components.
29. How do you handle global state in React?
Use Context API, Redux, or third-party libraries like Zustand or Recoil.
30. What is the difference between state and props in React?
- State: Managed within the component and mutable.
- Props: Passed from parent to child, immutable.
31. How do you test React components?
Use testing libraries like Jest and React Testing Library for unit and integration testing
32. What are render props in React?
Render props refer to a technique where a component shares logic by exposing a function as its child.
<DataProvider render={(data) => <List data={data} />} />
33. What is the difference between debounce and throttle? How are they used in React?
- Debounce: Delays execution until after a specified period of inactivity.
- Throttle: Ensures execution happens at most once in a specified time interval.
Used to optimize expensive operations like API calls during user input.
34. What is React’s PureComponent?
PureComponent is a class component that performs a shallow comparison of props and state to optimize rendering.
35. How do you manage focus in React applications?
Use the useRef
hook or React’s built-in focus management utilities.
36. What are React’s Strict Mode limitations?
Strict Mode runs code twice to highlight potential issues but only during development, which can lead to unexpected side effects.
37. How do you implement dark mode in React applications?
Use Context API or state to toggle themes and apply conditional class names or inline styles.
38. What is the significance of a React key in lists?
Keys help React identify which items have changed, added, or removed, improving update efficiency.
39. What are React DevTools, and how are they used?
React DevTools is a browser extension to inspect and debug React components, state, and props.
40. How do you handle animations in React?
Use libraries like React Transition Group or Framer Motion for animations.
41. What are React hooks rules?
- Only call hooks at the top level of a component.
- Only call hooks in React functions.
42. What is the difference between componentWillMount
and componentDidMount
?
componentWillMount
: Deprecated, ran before mounting.componentDidMount
: Runs after the component is mounted.
43. How do you manage routing in React?
Use react-router-dom
with <Routes>
and <Route>
components.
44. What is React Server Components?
React Server Components (RSC) allow rendering components on the server, reducing client-side JavaScript.
45. What is concurrent rendering in React?
Concurrent rendering improves UI responsiveness by interrupting and resuming rendering tasks.
46. What is suspense for data fetching?
Suspense simplifies asynchronous data fetching by displaying a fallback UI until the data is available.
47. How do you optimize list rendering in React?
Use React.memo
, virtualization libraries like React-Window, and proper key usage.
48. What are the advantages of using TypeScript with React?
- Better type checking.
- Improved code readability.
- Early bug detection.
49. What are dynamic imports in React?
Dynamic imports load components lazily for better performance:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
50. What are custom hooks in React?
Custom hooks are user-defined hooks that encapsulate reusable logic. Example:
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url).then((res) => res.json()).then(setData);
}, [url]);
return data;
};
Check out more blogs.