React JS Interview Questions and Answers
Q: What is lazy loading in React? Give an example.
A: Lazy loading in React is a design pattern that delays loading components until they're actually
needed, improving performance by reducing initial load time. Its commonly used in large
applications to split the code into smaller chunks.
**Example:**
```jsx
import React, { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<div>
<h1>Welcome</h1>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
```
Here, `LazyComponent` is only loaded when rendered, and until then, a fallback UI is shown.
Q: What is React Fiber?
A: React Fiber is the new reconciliation engine in React 16+. It improves rendering performance and
allows features like:
- Incremental rendering
- Better error handling
- Returning multiple elements from render()
- Support for async rendering (concurrent mode)
Fiber allows React to split work into units and spread them out over multiple frames, improving
responsiveness.
Q: What is the diffing algorithm in React?
A: React's diffing algorithm helps efficiently update the DOM by comparing the previous and next
virtual DOM trees.
Key optimizations:
- Two elements of different types produce different trees.
- Developers can use `key` prop in lists to hint React about element identity.
This makes Reacts updates predictable and performant.
Q: When to use Redux, useReducer, or Context API?
A: - **Redux**: Best for large-scale applications needing centralized global state, middleware (like
thunk/saga), or debugging tools.
- **useReducer**: Great for medium-complex components needing complex state logic; works well
with Context.
- **Context API**: Good for passing down props like themes or user info. Not optimal for
high-frequency state updates across deeply nested trees.
Q: What are Higher Order Components (HOCs)?
A: HOCs are functions that take a component and return a new component with additional props or
behavior.
**Example:**
```jsx
const withLogger = (WrappedComponent) => {
return function Enhanced(props) {
console.log('Props:', props);
return <WrappedComponent {...props} />;
};
};
```
Used for reusing logic across components.
Q: Performance optimization techniques in React?
A: 1. Code splitting with `React.lazy`
2. Memoization: `React.memo`, `useMemo`, `useCallback`
3. Virtualization (e.g., `react-window`)
4. Avoiding anonymous functions in render
5. Avoid unnecessary re-renders using `shouldComponentUpdate` or `React.memo`
6. Lazy load images/components
Q: What is SSR and CSR in React?
A: - **CSR (Client-Side Rendering)**: React app is rendered in browser after loading JavaScript.
Slower first load, better interactivity.
- **SSR (Server-Side Rendering)**: HTML is rendered on the server, improving performance and
SEO. Tools: Next.js.