1. What are the lifecycle methods in React class components?
Lifecycle methods are special methods in class components that run at different stages of a component’s life.
Phases & Methods
Mounting (when component is created)
-
constructor() -
static getDerivedStateFromProps() -
render() -
componentDidMount()
Updating (when props/state change)
-
static getDerivedStateFromProps() -
shouldComponentUpdate() -
render() -
getSnapshotBeforeUpdate() -
componentDidUpdate()
Unmounting (when component is removed)
-
componentWillUnmount()
Key Purpose
- Control component behavior at each stage
- Handle side effects, API calls, cleanup
2. What are the different phases of the React component lifecycle?
Mounting Phase
Component is created and inserted into the DOM.
Updating Phase
Occurs when state or props change.
Unmounting Phase
Component is removed from the DOM.
Error Handling Phase
-
componentDidCatch() -
getDerivedStateFromError()
Summary
Lifecycle = Mount → Update → Unmount (+ Error handling)
3. What is Reconciliation in React?
Definition
Reconciliation is the process React uses to compare old Virtual DOM with new Virtual DOM and update only the necessary parts.
Steps
- New Virtual DOM is created
- Compared with previous Virtual DOM (diffing)
- Minimal changes are calculated
- Real DOM is updated
Key Benefit
Efficient UI updates with minimal DOM operations
4. What is React Fiber?
Definition
React Fiber is the reimplementation of React’s core algorithm introduced in React 16.
Purpose
- Improve rendering performance
- Enable advanced features
Key Features
- Incremental rendering
- Ability to pause, resume, or abort rendering
- Better prioritization of updates
5. What is the main goal of React Fiber?
Primary Goal
To make rendering more flexible, efficient, and responsive.
Problems It Solves
- Blocking UI during heavy rendering
- Poor responsiveness
Key Concepts
- Prioritized updates
- Scheduling work
- Smooth user experience
6. What is useCallback and when should you use it?
Definition
useCallback is a Hook that memoizes a function so it is not recreated on every render.
Syntax
const memoizedFunction = useCallback(() => {
// logic
}, [dependencies]);
When to Use
- Passing functions to child components
- Preventing unnecessary re-renders
- Optimizing performance
Example
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
Key Insight
Useful when function identity matters (e.g., with React.memo)
7. What is useMemo and when should you use it?
Definition
useMemo memoizes the result of a computation.
Syntax
const value = useMemo(() => computeExpensiveValue(), [dependencies]);
When to Use
- Expensive calculations
- Derived data
- Avoid recomputation
Example
const squared = useMemo(() => num * num, [num]);
Key Difference from useCallback
- useMemo → memoizes value
- useCallback → memoizes function
8. What is useContext and when should you use it?
Definition
useContext is a Hook used to access context data directly without prop drilling.
Example
const value = useContext(MyContext);
When to Use
- Global state (theme, auth, language)
- Avoid prop drilling
Benefits
- Cleaner code
- Easier state sharing
9. What is useReducer and when is it preferred over useState?
Definition
useReducer is a Hook used for managing complex state logic.
Syntax
const [state, dispatch] = useReducer(reducer, initialState);
Example
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
default:
return state;
}
}
When to Use
- Complex state transitions
- Multiple related state variables
- State depends on previous state
useState vs useReducer
| Feature | useState | useReducer |
|---|---|---|
| Complexity | Simple | Complex |
| Logic | Minimal | Centralized |
| Use Case | Basic state | Advanced state |
10. What are Custom Hooks and how do you create one?
Definition
Custom Hooks are reusable functions that use React Hooks internally.
Purpose
- Reuse logic across components
- Keep code clean and modular
Naming Rule
Must start with use
Example
function useCounter() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
return { count, increment };
}
Usage
const { count, increment } = useCounter();
Benefits
- Code reuse
- Separation of concerns
- Better readability
11. What are the rules of Hooks?
Definition
Rules of Hooks are guidelines that ensure Hooks work correctly and predictably.
Rules
Only call Hooks at the top level
- Do not call inside loops, conditions, or nested functions
Only call Hooks from React functions
- Functional components
- Custom Hooks
Why Important
React relies on the order of Hook calls to maintain state correctly.
12. Why must Hooks be called at the top level?
Reason
React tracks Hooks based on their call order during rendering.
Problem if Violated
Calling Hooks conditionally changes order → leads to bugs and incorrect state mapping.
Example (Incorrect)
if (condition) {
useEffect(() => {});
}
Correct Approach
useEffect(() => {
if (condition) {
// logic
}
}, [condition]);
Key Insight
Consistent call order = predictable behavior
13. What is the difference between useEffect and useLayoutEffect?
useEffect
- Runs after the DOM is painted
- Non-blocking
- Used for API calls, subscriptions
useLayoutEffect
- Runs before the browser paints
- Blocks rendering
- Used for DOM measurements or layout updates
Comparison
| Feature | useEffect | useLayoutEffect |
|---|---|---|
| Timing | After paint | Before paint |
| Performance | Non-blocking | Blocking |
| Use Case | Side effects | Layout changes |
Summary
Use useEffect by default; use useLayoutEffect only when necessary.
14. What is forwardRef?
Definition
forwardRef allows passing a ref from parent to child component.
Example
const Input = React.forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
Use Case
- Access child DOM nodes
- Focus inputs from parent
Benefit
Enables better component composition and control
15. What are Higher Order Components (HOCs)?
Definition
A Higher Order Component is a function that takes a component and returns a new enhanced component.
Example
function withLogger(Component) {
return function Enhanced(props) {
console.log(props);
return <Component {...props} />;
};
}
Use Cases
- Authentication
- Logging
- Code reuse
Key Idea
Component → Enhance → New Component
16. What is the difference between HOCs and Render Props?
HOCs
- Wrap a component
- Return a new component
Render Props
- Pass a function as a prop
- Function returns JSX
Comparison
| Feature | HOC | Render Props |
|---|---|---|
| Pattern | Wrapper function | Function as prop |
| Usage | Component enhancement | Dynamic rendering |
| Flexibility | Moderate | High |
Summary
Both are used for code reuse, but Render Props are more flexible.
17. What is Render Props?
Definition
Render Props is a pattern where a function is passed as a prop to control rendering.
Example
function DataProvider({ render }) {
const data = "Hello";
return render(data);
}
<DataProvider render={(data) => <h1>{data}</h1>} />
Benefits
- Reusable logic
- Flexible rendering
- Better control over UI
18. What is the Composition Pattern in React?
Definition
Composition means combining small components to build complex UIs.
Example
function Card({ children }) {
return <div className="card">{children}</div>;
}
Key Idea
Instead of inheritance → use composition.
Benefits
- Reusability
- Flexibility
- Cleaner architecture
19. What is Code Splitting in React?
Definition
Code splitting is a technique to split bundles into smaller chunks and load them on demand.
Purpose
- Reduce initial load time
- Improve performance
Methods
- Dynamic import()
- React.lazy
- Route-based splitting
Example
const LazyComponent = React.lazy(() => import("./MyComponent"));
20. What is React.lazy?
Definition
React.lazy is used to dynamically load components.
Example
const MyComponent = React.lazy(() => import("./MyComponent"));
Usage with Suspense
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
Benefits
- Improves performance
- Reduces bundle size
- Enables lazy loading
21. What is React.Suspense?
Definition
React.Suspense is a component used to handle asynchronous loading of components or data.
Purpose
- Display fallback UI while waiting
- Manage lazy-loaded components
Example
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
Key Features
- Works with
React.lazy - Improves user experience
- Simplifies loading states
22. What is Lazy Loading?
Definition
Lazy loading is a technique where components or resources are loaded only when needed.
Purpose
- Reduce initial bundle size
- Improve performance
Example
const Component = React.lazy(() => import("./Component"));
Benefits
- Faster initial load
- Better resource utilization
23. What is Server-Side Rendering (SSR)?
Definition
SSR is rendering React components on the server instead of the browser.
Process
- Server generates HTML
- HTML sent to browser
- React attaches interactivity
Benefits
- Faster initial load
- Better SEO
- Improved performance on slow devices
Tools
- Next.js
- Remix
24. What is Hydration in React?
Definition
Hydration is the process where React attaches event listeners to server-rendered HTML.
How It Works
- HTML is already rendered
- React “hydrates” it to make it interactive
Key Insight
Without hydration → UI is static
25. What is Static Site Generation (SSG)?
Definition
SSG generates HTML at build time instead of runtime.
Process
- Pages are pre-built
- Served as static files
Benefits
- Extremely fast
- Better SEO
- Lower server load
Example Tools
- Next.js (getStaticProps)
26. What is Concurrent Mode in React?
Definition
Concurrent Mode is a set of features that allow React to interrupt and prioritize rendering tasks.
Purpose
- Improve responsiveness
- Prevent UI blocking
Key Features
- Time slicing
- Interruptible rendering
- Prioritized updates
Example Benefit
User input remains responsive even during heavy rendering
27. What is Strict Mode and its benefits?
Definition
Strict Mode is a tool that helps identify potential problems in an application during development.
Benefits
- Detect unsafe lifecycle methods
- Warn about deprecated APIs
- Highlight side effects
- Improve code quality
Example
<React.StrictMode>
<App />
</React.StrictMode>
Important Note
- Runs only in development
- No effect in production
28. What is the difference between PureComponent and Component?
Component
- Always re-renders when state/props change
PureComponent
- Performs shallow comparison of props and state
- Prevents unnecessary re-renders
Comparison
| Feature | Component | PureComponent |
|---|---|---|
| Rendering | Always | Conditional |
| Optimization | Manual | Automatic (shallow compare) |
| Performance | Less optimized | More optimized |
Key Insight
PureComponent improves performance but may fail with deep objects.
29. How do you prevent unnecessary re-renders?
Techniques
Use React.memo
- Prevent re-render if props unchanged
Use useMemo
- Cache computed values
Use useCallback
- Prevent function recreation
Avoid unnecessary state updates
- Update only when needed
Use keys properly
- Ensure stable identity
Split components
- Smaller components re-render less
Key Idea
Minimize changes → minimize re-renders
30. How does React handle re-rendering when state changes?
Process
- State is updated using setState/useState
- React schedules a re-render
- New Virtual DOM is created
- Diffing with previous Virtual DOM
- Only changed parts are updated in real DOM
Important Concepts
- Batching updates
- Asynchronous updates
- Efficient reconciliation
Key Insight
React does not update the entire DOM → only updates what changed
31. What are Derived States?
Definition
Derived state is state that is computed based on props or other state values instead of being stored independently.
Example
const [price, setPrice] = useState(100);
const [quantity, setQuantity] = useState(2);
const total = price * quantity; // derived state
Key Insight
Do not store derived values in state unless necessary.
Why Avoid Storing It?
- Can become inconsistent
- Leads to bugs and duplication
Best Practice
Compute derived values during render instead of storing them.
32. What is Computed State?
Definition
Computed state is similar to derived state; it refers to values calculated dynamically from existing state or props.
Example
const fullName = `${firstName} ${lastName}`;
Difference from Stored State
- Not stored explicitly
- Recomputed when dependencies change
Benefit
- Reduces redundancy
- Keeps data consistent
33. What is the difference between Client State and Server State?
Client State
- Stored in the browser
- UI-related data (form inputs, toggles)
Server State
- Comes from backend APIs
- Needs fetching, caching, syncing
Comparison
| Feature | Client State | Server State |
|---|---|---|
| Source | Local | Remote server |
| Examples | UI state | API data |
| Tools | useState | React Query, SWR |
| Sync | Immediate | Async |
Key Insight
Server state requires caching and synchronization strategies.
34. What is State Management in React?
Definition
State management is the process of handling and sharing data across components.
Types
Local State
- Managed within a component
Global State
- Shared across multiple components
Tools
- useState / useReducer
- Context API
- Redux, Zustand
Goal
Maintain predictable and consistent data flow.
35. What is Context API?
Definition
Context API allows sharing data globally without prop drilling.
Example
const ThemeContext = createContext();
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
Accessing Context
const theme = useContext(ThemeContext);
Use Cases
- Theme
- Authentication
- Language settings
36. When should you use Context over Redux?
Use Context When
- Small to medium applications
- Limited global state
- Simple state logic
Use Redux When
- Large applications
- Complex state transitions
- Need middleware, debugging tools
Summary
Context = simple global state
Redux = complex state management
37. What are the limitations of Context API?
Performance Issues
- All consumers re-render when value changes
Limited Features
- No built-in middleware
- No advanced debugging tools
Scalability
- Harder to manage in large apps
Summary
Good for simple use cases, not ideal for complex global state.
38. What are common React anti-patterns?
Common Mistakes
Storing derived state
- Leads to inconsistency
Mutating state directly
- Breaks React updates
Using index as key
- Causes rendering bugs
Too many props (prop drilling)
- Makes code hard to maintain
Large components
- Reduces reusability
Overusing useEffect
- Leads to unnecessary complexity
Key Insight
Follow best practices to keep code clean and predictable.
39. What is Immutability and why is it important in React?
Definition
Immutability means not modifying existing data, but creating new copies.
Example
setItems([...items, newItem]);
Why Important
- Enables efficient change detection
- Supports Virtual DOM diffing
- Prevents unexpected bugs
Key Benefit
React can easily detect changes → faster updates
40. Why should you not mutate state directly?
Problem
Direct mutation:
state.count = state.count + 1; // wrong
Issues
No re-render
- React may not detect changes
Unpredictable behavior
- Breaks state consistency
Debugging becomes hard
Correct Approach
setCount(count + 1);
Key Insight
React relies on immutability to track changes and update UI correctly.
41. What is Batching in React?
Definition
Batching is the process where React groups multiple state updates into a single re-render.
Example
setCount(c => c + 1);
setFlag(f => !f);
Behavior
- React combines updates → triggers only one render
- Improves performance
React 18 Enhancement
- Automatic batching for async operations (like promises, timeouts)
Benefit
Reduces unnecessary re-renders → faster UI
42. Difference Between Controlled and Uncontrolled Components (Rendering Perspective)
Controlled Components
- State is managed by React
- Every input change triggers state update → re-render
Uncontrolled Components
- State is managed by DOM
- React does not re-render on every input change
Comparison
| Feature | Controlled | Uncontrolled |
|---|---|---|
| Source of truth | React state | DOM |
| Re-render | Frequent | Minimal |
| Control | High | Low |
Key Insight
Controlled = predictable but more renders
Uncontrolled = fewer renders but less control
43. How do you handle asynchronous operations in React?
Common Methods
Using async/await
async function fetchData() {
const res = await fetch("/api");
}
Using useEffect
- Trigger async logic on mount/update
Using libraries
- Axios
- React Query
Best Practices
- Handle loading and error states
- Cancel requests when component unmounts
44. How do you fetch data using React Hooks?
Approach
Use useEffect + useState
Example
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
const res = await fetch("/api/data");
const result = await res.json();
setData(result);
setLoading(false);
}
fetchData();
}, []);
Key Points
- Runs on mount
- Updates state → triggers re-render
45. What is React Router?
Definition
React Router is a library used for handling navigation in React applications.
Purpose
- Enable multiple views in SPA
- Map URLs to components
Example
<Route path="/home" element={<Home />} />
Key Features
- Dynamic routing
- Nested routes
- Route parameters
46. What is Client-Side Routing?
Definition
Client-side routing is navigating between pages without reloading the entire page.
How It Works
- Browser URL changes
- React renders new component
- No full page refresh
Benefit
- Faster navigation
- Better user experience
47. What is the difference between <a> and <Link>?
<a> Tag
- Reloads the entire page
- Makes request to server
<Link> Component
- Uses client-side routing
- No page reload
Example
<Link to="/home">Go Home</Link>
Comparison
| Feature | <a> | <Link> |
|---|---|---|
| Reload page | Yes | No |
| Routing type | Server-side | Client-side |
| Performance | Slower | Faster |
48. What are Route Parameters?
Definition
Route parameters are dynamic values in URLs.
Example
<Route path="/user/:id" element={<User />} />
Accessing Params
const { id } = useParams();
Use Cases
- User profiles
- Product pages
49. What are Nested Routes?
Definition
Nested routes allow rendering components inside other components.
Example
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
</Route>
Benefit
- Better UI structure
- Reusable layouts
50. How do you redirect programmatically in React Router?
Method
Use useNavigate hook
Example
const navigate = useNavigate();
function handleClick() {
navigate("/home");
}
Use Cases
- After login
- After form submission
- Conditional navigation
Alternative
navigate("/home", { replace: true });
Key Insight
Programmatic navigation gives full control over routing logic.
51. What is useNavigate?
Definition
useNavigate is a Hook from React Router used to navigate programmatically between routes.
Syntax
const navigate = useNavigate();
Example
function handleLogin() {
navigate("/dashboard");
}
Features
- Navigate forward/backward
- Replace history entry
Example with options
navigate("/home", { replace: true });
Use Cases
- Redirect after login
- Conditional navigation
- Form submission redirects
52. What is the difference between <Switch> and <Routes>?
<Switch> (React Router v5)
- Renders the first matching route
- Uses
componentorrenderprops
<Routes> (React Router v6)
- Replaces
<Switch> - Uses
elementprop - Supports nested routes better
Comparison
| Feature | <Switch> | <Routes> |
|---|---|---|
| Version | v5 | v6 |
| Rendering | First match | Best match |
| Syntax | component/render | element |
| Nested routes | Limited | Improved |
Summary
<Routes> is modern, cleaner, and more powerful.
53. What are Private Routes?
Definition
Private routes restrict access to certain routes based on authentication or conditions.
Example
function PrivateRoute({ children }) {
return isAuthenticated ? children : <Navigate to="/login" />;
}
Use Case
- Protect dashboard
- Restrict admin pages
Key Idea
Conditional rendering of routes based on user state
54. What are Error Boundaries?
Definition
Error boundaries are React components that catch JavaScript errors in their child component tree.
Implementation
Class components only
class ErrorBoundary extends React.Component {
componentDidCatch(error, info) {
console.log(error);
}
render() {
return this.props.children;
}
}
Purpose
Prevent entire app from crashing
55. What errors do Error Boundaries catch?
Catches
- Errors in rendering
- Errors in lifecycle methods
- Errors in constructors
Does NOT Catch
- Event handler errors
- Async errors (setTimeout, promises)
- Server-side rendering errors
Key Insight
Only handles errors during rendering phase
56. Where should Error Boundaries be placed?
Placement Strategy
Top-level
- Wrap entire app to prevent crashes
Component-level
- Wrap critical UI parts (e.g., dashboard, widgets)
Best Practice
Use multiple boundaries for better isolation
Example
<ErrorBoundary>
<Dashboard />
</ErrorBoundary>
57. What is React DevTools?
Definition
React DevTools is a browser extension used to inspect React component trees.
Features
- View component hierarchy
- Inspect props and state
- Debug performance
- Highlight re-renders
Benefit
Helps developers debug and optimize React apps
58. Difference Between useEffect Cleanup and componentWillUnmount
useEffect Cleanup
useEffect(() => {
return () => {
console.log("Cleanup");
};
}, []);
componentWillUnmount
componentWillUnmount() {
console.log("Cleanup");
}
Comparison
| Feature | useEffect Cleanup | componentWillUnmount |
|---|---|---|
| Component Type | Functional | Class |
| Timing | Before unmount & re-run | Only before unmount |
| Usage | Modern approach | Legacy approach |
Key Insight
useEffect cleanup is more flexible and widely used today
59. What are Portals used for?
Definition
Portals allow rendering components outside the parent DOM hierarchy.
Example
ReactDOM.createPortal(<Modal />, document.getElementById("root"));
Use Cases
- Modals
- Tooltips
- Dropdowns
Benefits
- Avoid CSS issues (z-index, overflow)
- Better UI layering
60. What is the Windowing Technique?
Definition
Windowing (or virtualization) is a technique where only visible items in a list are rendered.
Problem Solved
Rendering large lists can slow down performance.
Solution
Render only items currently visible on screen.
Example Libraries
- react-window
- react-virtualized
Benefits
- Improved performance
- Reduced memory usage
- Faster rendering
Example Scenario
List of 10,000 items → render only 20 visible items
61. What is Virtualization in React?
Definition
Virtualization (windowing) is a technique where React renders only the visible portion of a large list instead of the entire dataset.
Problem
Rendering thousands of DOM nodes → performance issues.
Solution
Render only items currently in the viewport.
Example Libraries
- react-window
- react-virtualized
Benefits
- Faster rendering
- Lower memory usage
- Smooth scrolling
Key Insight
Only visible UI matters → render less, perform more.
62. What is Memoization in React and why is it useful?
Definition
Memoization is a technique to cache results of computations or components to avoid unnecessary recalculations.
Tools in React
-
React.memo -
useMemo -
useCallback
Why Useful
- Improves performance
- Prevents unnecessary re-renders
- Optimizes expensive operations
Example
const value = useMemo(() => expensiveFunction(data), [data]);
Key Insight
Recompute only when dependencies change.
63. What are Synthetic Events and how do they work?
Definition
Synthetic events are React’s cross-browser wrapper around native DOM events.
How They Work
- React creates a unified event system
- Normalizes event behavior across browsers
- Uses event delegation (single listener at root)
Example
function handleClick(e) {
console.log(e.type);
}
Benefits
- Consistent API
- Better performance
- Easier event handling
64. What are Controlled Inputs and how does React manage their value?
Definition
Controlled inputs are form elements whose value is controlled by React state.
Example
const [name, setName] = useState("");
<input value={name} onChange={e => setName(e.target.value)} />
How React Manages It
- Input value tied to state
- onChange updates state
- State update triggers re-render
Benefits
- Full control over form data
- Easy validation
- Predictable behavior
65. How do you manage multiple input fields in a form?
Approach
Use a single state object to store all form values.
Example
const [form, setForm] = useState({
name: "",
email: ""
});
function handleChange(e) {
setForm({
...form,
[e.target.name]: e.target.value
});
}
Input Fields
<input name="name" onChange={handleChange} />
<input name="email" onChange={handleChange} />
Benefits
- Scalable form handling
- Cleaner code
- Easier updates
66. Difference Between React Node, React Element, and React Component
React Node
Anything that can be rendered:
- Strings, numbers
- Elements
- Arrays
React Element
- Object representation of UI
- Created using JSX or createElement
React Component
- Function or class returning elements
Comparison
| Feature | React Node | React Element | React Component |
|---|---|---|---|
| Type | Any renderable | Object | Function/Class |
| Role | Output | UI description | UI logic |
Summary
Component → returns Element → becomes Node
67. What is createElement vs cloneElement?
createElement
- Creates a new React element
React.createElement("h1", null, "Hello");
cloneElement
- Clones an existing element and modifies props
React.cloneElement(element, { className: "new" });
Key Difference
| Feature | createElement | cloneElement |
|---|---|---|
| Purpose | Create new element | Modify existing |
| Use Case | JSX conversion | Enhance children |
68. Difference Between Imperative and Declarative Programming
Imperative
- Focus on how to do something
- Step-by-step instructions
Example (DOM)
document.getElementById("app").innerHTML = "Hello";
Declarative
- Focus on what the UI should be
Example (React)
<h1>Hello</h1>
Comparison
| Feature | Imperative | Declarative |
|---|---|---|
| Approach | How | What |
| Complexity | Higher | Lower |
| Example | DOM manipulation | React |
Key Insight
React is declarative → easier to reason about UI
69. What is React’s One-Way Data Flow?
Definition
Data flows from parent to child components only.
Example
<Child name="Jitendra" />
Key Characteristics
- Unidirectional flow
- Predictable state management
- Easier debugging
Benefit
Changes are easier to track and control
70. What are the benefits of using TypeScript with React?
Definition
TypeScript is a superset of JavaScript that adds static typing.
Benefits
Type Safety
- Catch errors at compile time
Better Developer Experience
- Autocomplete
- IntelliSense
Improved Maintainability
- Clear data structures
Refactoring Support
- Safer code changes
Example
type Props = {
name: string;
};
function Greeting({ name }: Props) {
return <h1>{name}</h1>;
}
Key Insight
TypeScript makes large React applications more robust and scalable