1. What is React Concurrent Rendering?
Definition
Concurrent Rendering in React is a rendering mode that allows React to pause, interrupt, and resume rendering work to keep the UI responsive.
Core Idea
Instead of blocking the main thread, React can:
- Work on multiple updates simultaneously
- Pause low-priority work
- Resume later without losing progress
Key Features
- Interruptible rendering
- Prioritized updates
- Improved user experience
Example
Typing in a search box:
- Input update → high priority
- Filtering a large list → low priority
React ensures typing stays smooth.
Why It Matters
- Improves responsiveness
- Enables smoother interactions
- Handles large UI updates efficiently
2. How does React prioritize updates in concurrent mode?
Concept
React uses a priority-based scheduling system.
Mechanism
React assigns updates to different priority levels (lanes):
- High priority → user input, clicks
- Medium priority → data updates
- Low priority → background rendering
How It Works
- Scheduler evaluates urgency
- High-priority work interrupts low-priority work
- Low-priority work resumes later
Example
Typing happens immediately, while list updates may be delayed.
Benefit
- Prevents UI lag
- Ensures important updates are processed first
3. What is time slicing in React?
Definition
Time slicing is a technique where React breaks rendering work into small chunks and executes them over multiple frames.
How It Works
- Work is divided into smaller units
- React yields control to the browser between chunks
- Work continues later
Example
Rendering a large list:
- Without time slicing → UI freezes
- With time slicing → UI remains responsive
Advantages
- Keeps application responsive
- Avoids blocking the main thread
4. What is the difference between async rendering and synchronous rendering?
Comparison
| Feature | Synchronous Rendering | Concurrent (Async) Rendering |
|---|---|---|
| Execution | Blocking | Non-blocking |
| Interruptible | No | Yes |
| UI Responsiveness | Can freeze | Smooth |
| Priority Handling | None | Supported |
| Rendering Style | All at once | Incremental |
Summary
Synchronous rendering is simpler but blocking. Concurrent rendering is more advanced and improves responsiveness.
5. What is React Fiber architecture?
Definition
Fiber is the reconciliation engine of React introduced in React 16.
Core Idea
It replaces the stack-based approach with a linked structure called the Fiber tree.
Key Features
- Incremental rendering
- Priority scheduling
- Pause and resume capability
Structure
Each Fiber node contains:
- Component type
- State
- Props
- References to child and sibling nodes
Two Phases
- Render Phase (Reconciliation)
- Calculates changes
- Can be paused
- Commit Phase
- Applies changes to the DOM
- Cannot be interrupted
Purpose
- Enables concurrent rendering
- Improves control over rendering work
6. How does the diffing algorithm work in React?
Definition
React uses a heuristic diffing algorithm to compare the previous and new Virtual DOM.
Core Principle
Instead of using an expensive algorithm, React optimizes comparison to O(n) using assumptions.
Steps
- Compare root elements
- If types differ → replace entire subtree
- If same → update attributes
- Recursively compare children
Example
<div>Old</div>
<div>New</div>
Only the text content updates.
Benefit
- Fast updates
- Efficient DOM manipulation
7. What rules are covered by the diffing algorithm?
Key Rules
- Different element types → replace entire subtree
<div /> → <span />
- Same type → update only changed attributes
- Keys are important for lists
<li key="1">Item</li>
- Without keys, React uses index-based comparison, which can lead to inefficient updates
Insight
Keys help React identify elements uniquely and optimize rendering.
8. What are the performance trade-offs of the Virtual DOM?
Advantages
- Efficient updates
- Declarative UI model
- Platform independence
Trade-offs
- Additional memory usage
- Overhead of maintaining Virtual DOM
- Not always faster for very small updates
Insight
Virtual DOM improves performance in most real-world applications, especially large ones.
9. How does React batch updates?
Definition
Batching means grouping multiple state updates into a single render cycle.
How It Works
setCount(1);
setFlag(true);
These updates are processed together in one render.
Types
- Automatic batching in React 18 and later
- Works across events, promises, and timeouts
Before vs After React 18
- Earlier: async updates were not batched
- Now: most updates are batched automatically
Benefit
- Reduces number of renders
- Improves performance
10. What is selective hydration?
Definition
Selective Hydration in React allows React to hydrate only the most important parts of the UI first.
Context
Used in server-side rendering.
How It Works
- Server sends HTML
- React attaches interactivity gradually
- Prioritizes important components
Example
- Interactive elements become usable first
- Less critical parts load later
Benefits
- Faster interactivity
- Better performance on slow devices
- Improved user experience
11. How does React handle long-running tasks without blocking the UI?
Definition
React avoids blocking the UI by breaking long-running tasks into smaller units and scheduling them efficiently.
Core Mechanisms
1. Concurrent Rendering
In React, rendering work can be paused and resumed. This ensures that long tasks do not block user interactions.
2. Time Slicing
- Work is split into chunks
- React yields control back to the browser between chunks
- The browser can handle user input in between
3. Scheduler
React uses an internal scheduler to:
- Assign priorities
- Interrupt low-priority tasks
- Resume them later
Example
Rendering a large list:
- Instead of blocking the thread, React renders it incrementally
Result
- Smooth UI
- No freezing during heavy updates
13. What is server streaming in React?
Definition
Server streaming is a technique where the server sends HTML to the client in chunks instead of waiting for the entire page to be ready.
How It Works
- Server starts sending HTML early
- React streams parts of the UI progressively
- Client renders content as it arrives
Key Technology
- Streaming APIs (e.g.,
renderToPipeableStream)
Example
- Header loads immediately
- Main content loads later
- Footer loads last
Benefits
- Faster Time to First Byte (TTFB)
- Faster perceived load time
- Better user experience
14. What is React Server Components?
Definition
React Server Components (RSC) allow components to be rendered on the server instead of the client.
Core Idea
- Some components run only on the server
- They send serialized output to the client
Characteristics
- No client-side JavaScript for those components
- Direct access to server resources (DB, APIs)
- Smaller bundle size
Example
- Product list fetched directly from database on server
Benefits
- Reduced bundle size
- Improved performance
- Better data fetching efficiency
15. What are the differences between CSR, SSR, and SSG?
Definitions
- CSR (Client-Side Rendering): UI rendered in browser
- SSR (Server-Side Rendering): HTML generated per request on server
- SSG (Static Site Generation): HTML generated at build time
Comparison
| Feature | CSR | SSR | SSG |
|---|---|---|---|
| Rendering Location | Client | Server | Build time |
| Initial Load | Slower | Faster | Fastest |
| SEO | Poor | Good | Excellent |
| Data Freshness | High | High | Low (unless rebuilt) |
| Server Load | Low | High | Very low |
Summary
- CSR → dynamic apps
- SSR → SEO + dynamic content
- SSG → static, fast content
16. How does React handle hydration mismatches?
Definition
A hydration mismatch occurs when server-rendered HTML differs from client-rendered content.
Causes
- Non-deterministic values (e.g.,
Date,Math.random) - Different data on server vs client
- Conditional rendering differences
How React Handles It
- Logs warnings in development
- Attempts to recover by re-rendering mismatched parts
Strategies to Avoid
- Ensure consistent rendering on server and client
- Avoid side effects during render
- Use stable data
Example
Incorrect:
<div>{Math.random()}</div>
Best Practice
Use effects or client-only logic for dynamic values.
17. What is React Suspense for data fetching?
Definition
Suspense in React allows components to "wait" for asynchronous data before rendering.
Core Idea
- Component "suspends" while data is loading
- A fallback UI is shown
Example
<Suspense fallback={<Loader />}>
<UserProfile />
</Suspense>
How It Works
- Component throws a Promise
- React catches it
- Shows fallback until resolved
Benefits
- Declarative loading states
- Cleaner async handling
- Avoids complex loading logic
18. What are render waterfalls and how do you avoid them?
Definition
A render waterfall occurs when components fetch data sequentially instead of in parallel.
Problem
- Parent fetches → renders
- Child fetches → renders
- Leads to delays
Example Flow
- Parent loads
- Child starts fetching after parent renders
- Delay accumulates
Solutions
1. Parallel Data Fetching
Fetch all data upfront
2. Suspense
Coordinate async rendering
3. Server Components
Fetch data on server
4. Preloading
Start fetching early
Result
- Reduced latency
- Faster rendering
19. How do you optimize large React applications?
Key Strategies
1. Code Splitting
- Use
React.lazyand dynamic imports
2. Memoization
-
React.memo,useMemo,useCallback
3. Virtualization
- Render only visible items (e.g., large lists)
4. Efficient State Management
- Avoid unnecessary global state
- Normalize state
5. Avoid Re-renders
- Use proper keys
- Optimize props
6. Concurrent Features
- Use transitions
- Use Suspense
7. Bundle Optimization
- Tree shaking
- Remove unused dependencies
Outcome
- Faster load times
- Better runtime performance
20. What are common performance bottlenecks in React apps?
Common Issues
1. Unnecessary Re-renders
- Caused by changing props or state unnecessarily
2. Large Component Trees
- Deep nesting increases rendering cost
3. Inefficient List Rendering
- Missing keys
- Rendering large lists without virtualization
4. Heavy Computation in Render
- Expensive calculations inside components
5. Frequent State Updates
- Too many updates causing multiple renders
6. Large Bundle Size
- Slow initial load
7. Blocking Main Thread
- Long synchronous operations
Detection Tools
- React DevTools Profiler
- Performance tab in browser
Fix Strategies
- Memoization
- Lazy loading
- Debouncing/throttling
- Splitting components
21. How do you debug performance issues in React?
Definition
Debugging performance issues involves identifying slow renders, unnecessary updates, and inefficient logic in a React application.
Key Tools
1. React DevTools Profiler
- Tracks component render times
- Shows which components re-rendered and why
2. Browser Performance Tab
- Analyze CPU usage, memory, and blocking tasks
3. Console Logging / Markers
- Track render frequency manually
Process
Step 1: Identify slow components
- Use profiler to find components with high render time
Step 2: Detect unnecessary re-renders
- Check props/state changes
- Use "why did this render" tools
Step 3: Analyze component tree
- Look for deep or frequently updating trees
Step 4: Optimize
- Apply memoization
- Split components
- Use lazy loading
Common Fixes
-
React.memo -
useMemo,useCallback - Virtualization for large lists
22. What is memoization vs caching in React?
Definition
Memoization
- Stores results of function calls based on inputs
Caching
- Stores data (e.g., API responses) for reuse
Key Differences
| Feature | Memoization | Caching |
|---|---|---|
| Scope | Function-level | Data-level |
| Purpose | Avoid recomputation | Avoid refetching |
| Example | useMemo | API cache |
In React
Memoization Tools
-
useMemo→ memoize values -
useCallback→ memoize functions -
React.memo→ memoize components
Caching Examples
- Storing API responses in state or libraries
Insight
Memoization improves rendering performance, while caching improves data-fetch efficiency.
23. How do you prevent unnecessary context re-renders?
Problem
When context value changes, all consuming components re-render.
Solutions
1. Split Contexts
- Separate concerns into multiple contexts
2. Memoize Context Value
const value = useMemo(() => ({ user }), [user]);
3. Use Selector Pattern
- Consume only required parts of context
4. Use External State Libraries
- For fine-grained updates
Best Practice
Keep context values stable and minimal.
24. What are the pitfalls of using Context for global state?
Issues
1. Performance Problems
- All consumers re-render on any change
2. Lack of Granularity
- No built-in selective subscriptions
3. Hard to Scale
- Complex logic becomes difficult to manage
4. Debugging Difficulty
- No advanced devtools like Redux
5. Overuse
- Using Context for frequently changing state is inefficient
Conclusion
Context is best for low-frequency, simple global state (e.g., theme, auth).
25. What is state normalization?
Definition
State normalization is the process of structuring state in a flat and organized way, similar to a database.
Example
Before (Nested)
{
"posts": [
{ "id": 1, "author": { "id": 1, "name": "A" } }
]
}
After (Normalized)
{
"posts": { "1": { "id": 1, "authorId": 1 } },
"users": { "1": { "id": 1, "name": "A" } }
}
Benefits
- Avoids duplication
- Easier updates
- Improves performance
Use Case
Large applications with relational data
26. What is the difference between Redux and Context API?
Definitions
- Redux: External state management library
- Context API: Built-in React feature for passing data
Comparison
| Feature | Redux | Context API |
|---|---|---|
| Type | Library | Built-in |
| Performance | Optimized | Can re-render widely |
| DevTools | Advanced | Limited |
| Middleware | Supported | Not supported |
| Scalability | High | Moderate |
Insight
Redux is more suitable for complex state logic, while Context is simpler.
27. When should Redux be preferred over Context?
Use Redux When
1. Large-scale applications
- Complex state interactions
2. Frequent state updates
- Need fine-grained control
3. Advanced debugging required
- Time-travel debugging
4. Middleware needed
- Logging, async handling
5. Shared state across many components
Avoid Redux When
- Small applications
- Simple state needs
28. What is Redux Toolkit?
Definition
Redux Toolkit (RTK) is the official, recommended way to write Redux logic.
Key Features
1. Simplified Store Setup
-
configureStore
2. Slice-based Structure
-
createSlicecombines reducer + actions
3. Built-in Immer
- Write mutable logic safely
4. DevTools Integration
Example
const slice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => { state.value += 1 }
}
});
Benefits
- Less boilerplate
- Easier to maintain
- Standardized patterns
29. What is Redux Thunk?
Definition
Redux Thunk is middleware that allows dispatching functions instead of plain actions.
Purpose
Handles asynchronous logic like API calls.
How It Works
- Action creator returns a function
- Function receives
dispatchandgetState
Example
const fetchData = () => async (dispatch) => {
const data = await fetch('/api');
dispatch({ type: 'SET_DATA', payload: data });
};
Use Cases
- API calls
- Delayed actions
Advantage
- Simple and easy to use
30. What is Redux Saga?
Definition
Redux Saga is middleware for handling side effects using generator functions.
Core Idea
Uses yield to manage async flows in a declarative way.
Example
function* fetchDataSaga() {
const data = yield call(api);
yield put({ type: 'SET_DATA', payload: data });
}
Key Concepts
-
call→ API calls -
put→ dispatch actions -
takeLatest→ handle latest request
Advantages
- Better for complex async flows
- Improved readability for workflows
Trade-off
- Steeper learning curve compared to Thunk
31. What is the difference between Redux Saga and Redux Thunk?
Definitions
- Redux Thunk: Middleware that allows dispatching functions for async logic
- Redux Saga: Middleware that uses generator functions to manage side effects
Key Differences
| Feature | Redux Thunk | Redux Saga |
|---|---|---|
| Approach | Function-based | Generator-based |
| Complexity | Simple | Advanced |
| Async Handling | Imperative | Declarative |
| Control Flow | Limited | Powerful (cancel, retry, debounce) |
| Learning Curve | Low | High |
Example
Thunk
const fetchData = () => async (dispatch) => {
const data = await api();
dispatch({ type: 'SET_DATA', payload: data });
};
Saga
function* fetchDataSaga() {
const data = yield call(api);
yield put({ type: 'SET_DATA', payload: data });
}
When to Use
- Thunk → simple async logic
- Saga → complex workflows (retry, parallel tasks, cancellation)
32. What are selectors and why are they important?
Definition
Selectors are functions used to extract and derive data from the state.
Example
const getUser = (state) => state.user;
Importance
1. Encapsulation
- Hide state structure
2. Reusability
- Same logic used across components
3. Performance
- Avoid unnecessary recalculations
4. Maintainability
- Centralized data access logic
Insight
Selectors act as a layer between UI and state.
33. What is Reselect?
Definition
Reselect is a library used to create memoized selectors.
Purpose
- Prevent unnecessary recalculations
- Improve performance
Example
import { createSelector } from 'reselect';
const selectItems = state => state.items;
const selectExpensive = createSelector(
[selectItems],
(items) => items.filter(i => i.active)
);
Key Feature
- Recomputes only when inputs change
Benefit
- Efficient derived state computation
34. What is Flux architecture?
Definition
Flux is an architectural pattern for managing data flow in applications.
Core Principle
Unidirectional data flow
Components
- Actions
- Describe events
- Dispatcher
- Central hub
- Stores
- Hold state
- View (React)
- UI layer
Flow
Action → Dispatcher → Store → View
Benefit
- Predictable state updates
- Easier debugging
35. What is the mental model of Redux?
Core Idea
Redux follows a strict unidirectional data flow with a single source of truth.
Key Concepts
1. Store
- Holds entire state
2. Actions
- Describe what happened
3. Reducers
- Pure functions that update state
4. Dispatch
- Sends actions to reducers
Flow
UI → dispatch(action) → reducer → new state → UI updates
Principles
- Single source of truth
- State is immutable
- Changes via pure functions
Insight
Redux behaves like a state machine.
36. What is the difference between Redux and MobX?
Definitions
- Redux: Predictable state container with strict rules
- MobX: Reactive state management using observable data
Comparison
| Feature | Redux | MobX |
|---|---|---|
| Paradigm | Functional | Reactive |
| State Updates | Immutable | Mutable |
| Boilerplate | More | Less |
| Learning Curve | Moderate | Easy |
| Debugging | Excellent | Moderate |
Insight
- Redux → strict, predictable
- MobX → flexible, automatic reactivity
37. What is optimistic UI updating?
Definition
Optimistic UI updates immediately reflect a successful result before the server confirms it.
Example
- User likes a post
- UI updates instantly
- Server request happens in background
Flow
- Update UI
- Send request
- Rollback if error
Benefits
- Faster perceived performance
- Better user experience
Risk
- Requires rollback handling
38. What is stale-while-revalidate pattern?
Definition
A caching strategy where stale data is shown first, then updated in the background.
Flow
- Show cached data
- Fetch fresh data
- Update UI when new data arrives
Example
- Show old list instantly
- Refresh silently
Benefits
- Fast UI response
- Fresh data eventually
Insight
Balances speed and accuracy
39. What is React Query / TanStack Query?
Definition
TanStack Query (formerly React Query) is a data-fetching and state management library for server state.
Core Features
1. Caching
- Automatic caching of API responses
2. Background Refetching
- Keeps data fresh
3. Synchronization
- Syncs server and UI state
4. Built-in Status Handling
- Loading, error, success
Example
const { data, isLoading } = useQuery(['users'], fetchUsers);
Benefits
- Eliminates manual data-fetch logic
- Handles caching, retries, refetching
40. What is SWR?
Definition
SWR (Stale-While-Revalidate) is a data-fetching library built by Vercel.
Core Idea
Implements stale-while-revalidate strategy.
Example
const { data } = useSWR('/api/user', fetcher);
Features
- Fast caching
- Auto revalidation
- Focus re-fetch
- Interval updates
Benefits
- Simple API
- Real-time data freshness
41. What is server state management?
Definition
Server state management refers to handling data that originates from a server (APIs, databases) and synchronizing it with the UI in a React application.
Key Characteristics
- Stored remotely (not in client memory)
- Asynchronous in nature
- Shared across users
- Can become stale
Challenges
- Caching
- Synchronization
- Refetching
- Error handling
Solutions / Tools
- TanStack Query
- SWR
Example
Fetching user data from an API and keeping it updated automatically.
Insight
Server state is different from client state (UI state) and requires specialized handling.
42. How do you handle cache invalidation in React apps?
Definition
Cache invalidation ensures that stale data is replaced with fresh data when needed.
Strategies
1. Time-based Invalidation
- Cache expires after a duration (TTL)
2. Event-based Invalidation
- Invalidate after mutations (create/update/delete)
3. Manual Invalidation
- Explicitly clear cache
Example (React Query)
queryClient.invalidateQueries(['users']);
Best Practices
- Invalidate only affected queries
- Avoid over-fetching
- Use background refetching
Insight
Incorrect invalidation can lead to stale UI or unnecessary network calls.
43. What are race conditions in React data fetching?
Definition
A race condition occurs when multiple async requests compete, and responses arrive in an unpredictable order.
Problem
Older request finishes after a newer one and overwrites correct data.
Example
- User types quickly in search
- Request A (old) returns after Request B (new)
- UI shows outdated result
Solutions
1. Abort Previous Requests
- Use
AbortController
2. Track Latest Request
- Ignore outdated responses
3. Use Libraries
- TanStack Query handles this automatically
Insight
Race conditions lead to inconsistent UI and must be controlled.
44. What is request deduplication?
Definition
Request deduplication ensures that multiple identical requests are combined into one network call.
Problem
Multiple components request the same data simultaneously.
Solution
- Share the same request result
Example
- Two components fetch
/users - Only one API call is made
Tools
- TanStack Query
- SWR
Benefit
- Reduces network load
- Improves performance
45. What is React Router v6 architecture?
Definition
React Router v6 introduces a simplified and declarative routing system.
Key Changes
1. Nested Routing
- Routes defined hierarchically
2. Element-based API
<Route path="/home" element={<Home />} />
3. Layout Routes
- Shared UI across routes
4. Data APIs (v6.4+)
- Loaders and actions for data fetching
Core Concepts
- Routes as components
- Matching based on best fit
Benefits
- Cleaner syntax
- Better performance
- Improved scalability
46. How do you implement route guards in React Router?
Definition
Route guards restrict access to certain routes based on conditions (e.g., authentication).
Approach
1. Wrapper Component
function ProtectedRoute({ children }) {
return isAuth ? children : <Navigate to="/login" />;
}
2. Usage
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
Alternative
- Use loaders (v6.4+) for redirect logic
Use Cases
- Authentication
- Role-based access
47. How do you manage 404 and fallback routes?
Definition
Handling routes that do not match any defined path.
Implementation
Catch-all Route
<Route path="*" element={<NotFound />} />
Fallback UI
- Show loading or placeholder for lazy components
Best Practices
- Place wildcard route last
- Provide user-friendly error page
48. What is code splitting by route?
Definition
Code splitting by route means loading JavaScript only for the current route instead of the entire app.
How It Works
- Split bundles per route
- Load on demand
Example
const Home = React.lazy(() => import('./Home'));
Benefits
- Smaller initial bundle
- Faster load time
Use Case
Large applications with many pages
49. What are dynamic imports?
Definition
Dynamic imports allow loading JavaScript modules at runtime instead of at build time.
Syntax
import('./module').then(module => { ... });
In React
Used with React.lazy for code splitting.
Benefits
- Reduces initial load size
- Loads code only when needed
50. What is tree shaking?
Definition
Tree shaking is a build optimization technique that removes unused code from the final bundle.
How It Works
- Based on ES module static analysis
- Eliminates unused exports
Example
import { usedFunction } from './utils';
Unused functions are removed.
Requirements
- ES modules (
import/export) - Modern bundlers (Webpack, Vite, etc.)
Benefits
- Smaller bundle size
- Faster application load
51. What is bundle splitting strategy?
Definition
Bundle splitting strategy is the approach of dividing application code into smaller bundles to optimize loading performance in a React application.
Types of Splitting
1. Entry-based Splitting
- Separate bundles for different entry points
2. Route-based Splitting
- Load code per route
3. Component-based Splitting
- Lazy load specific components
Example
const Dashboard = React.lazy(() => import('./Dashboard'));
Strategy Goals
- Reduce initial bundle size
- Load only necessary code
- Improve Time to Interactive (TTI)
Best Practices
- Split large features
- Avoid too many small chunks
- Use caching effectively
52. What are micro-frontends?
Definition
Micro-frontends is an architectural style where a frontend application is divided into smaller, independent applications.
Core Idea
- Each team owns a part of the UI
- Applications are independently developed and deployed
Characteristics
- Independent builds
- Decoupled codebases
- Technology flexibility
Example
- E-commerce app:
- Cart → one app
- Product listing → another
- Checkout → another
Benefits
- Scalability
- Team autonomy
- Faster development cycles
Challenges
- Integration complexity
- Shared dependencies
- Consistent UI/UX
53. How does React support micro-frontends?
Approach
React does not provide built-in micro-frontend support but integrates well with patterns and tools.
Techniques
1. Module Federation (Webpack)
- Load remote components at runtime
2. Multiple React Apps
- Compose apps via container
3. Iframes (less common)
- Isolated applications
4. Shared Component Libraries
- Common UI components across apps
Key Considerations
- Shared dependencies (React version)
- State management across apps
- Routing coordination
Benefit
Flexible integration of independent UI modules
54. What are web components and how do you integrate them with React?
Definition
Web Components are reusable, encapsulated custom HTML elements built using browser standards.
Technologies
- Custom Elements
- Shadow DOM
- HTML Templates
Example
<my-button></my-button>
Integration with React
1. Use like normal HTML elements
<my-button></my-button>
2. Handle Props via Attributes
3. Use Refs for Events
ref.current.addEventListener('click', handler);
Challenges
- Event handling differences
- Prop vs attribute mismatch
Benefit
Framework-agnostic reusable components
55. What is forward compatibility in React?
Definition
Forward compatibility means code written today continues to work with future versions of React.
Example
- Using modern APIs like hooks instead of deprecated lifecycle methods
Strategies
- Follow best practices
- Avoid deprecated APIs
- Use official recommendations
Benefit
- Easier upgrades
- Reduced maintenance
56. What is backward compatibility in React?
Definition
Backward compatibility ensures newer versions of React still support older code.
Example
- Legacy class components still work in newer versions
Importance
- Smooth migration
- Stability for large apps
Limitation
- Not guaranteed for deprecated features forever
57. What are breaking changes in React upgrades and how do you handle them?
Definition
Breaking changes are updates that modify or remove existing behavior, causing old code to fail.
Examples
- Deprecated lifecycle methods removed
- Changes in rendering behavior
Handling Strategy
1. Read Release Notes
- Understand changes
2. Use Codemods
- Automate migration
3. Incremental Upgrades
- Upgrade step by step
4. Testing
- Ensure app stability
Best Practice
Avoid deprecated APIs early
58. What is React Strict Mode double rendering and why does it happen?
Definition
Strict Mode in React intentionally renders components twice in development.
Purpose
- Detect side effects
- Ensure components are pure
What Happens
- Functions run twice (development only)
- Effects are mounted and cleaned up twice
Example
useEffect(() => {
console.log('runs twice in dev');
}, []);
Why It Exists
- Helps identify unsafe patterns
- Prepares code for concurrent rendering
Important Note
- Does not affect production
59. What is hydration error and how do you fix it?
Definition
A hydration error occurs when server-rendered HTML does not match client-rendered output.
Causes
- Dynamic values (Date, random)
- Different data on server/client
- Conditional rendering differences
Fix Strategies
1. Ensure Deterministic Rendering
- Same output on server and client
2. Move Client-only Logic to Effects
useEffect(() => {
setValue(Date.now());
}, []);
3. Use Stable Data Sources
4. Debug Warnings
- React logs mismatch issues
Result
Consistent UI without errors
60. What is controlled rehydration?
Definition
Controlled rehydration is the process of managing how and when server-rendered content becomes interactive on the client.
Context
Used in Server-Side Rendering (SSR).
How It Works
- Hydration happens selectively
- Priority given to important UI parts
Techniques
1. Selective Hydration
- Hydrate critical components first
2. Suspense Boundaries
- Delay less important parts
3. Streaming + Progressive Hydration
- Combine with server streaming
Benefits
- Faster interactivity
- Better performance
- Improved user experience
61. What is render hijacking?
Definition
Render hijacking is a pattern where a component (usually via a Higher-Order Component) controls or overrides the rendering logic of another component.
Core Idea
- Intercept rendering
- Modify output conditionally
Example
const withAuth = (Component) => (props) => {
if (!props.isAuth) return <Login />;
return <Component {...props} />;
};
Use Cases
- Authentication checks
- Feature flags
- Conditional rendering
Drawbacks
- Reduces transparency
- Harder to debug
- Can create tight coupling
62. What are Higher-Order Components (HOCs) and their drawbacks?
Definition
A Higher-Order Component (HOC) is a function that takes a component and returns a new enhanced component.
Pattern
const Enhanced = withFeature(Component);
Use Cases
- Code reuse
- Cross-cutting concerns (auth, logging)
Drawbacks
1. Wrapper Hell
- Deep nesting of components
2. Props Collision
- Conflicting prop names
3. Debugging Difficulty
- Hard to trace component hierarchy
4. Reduced Readability
- Logic spread across layers
Modern Alternative
- Hooks in React
63. What are render props and their drawbacks?
Definition
Render props is a pattern where a component receives a function as a prop to control what to render.
Example
<DataFetcher render={(data) => <List data={data} />} />
Use Cases
- Sharing logic
- Flexible rendering
Drawbacks
1. Nested JSX (Callback Hell)
- Reduces readability
2. Performance Issues
- New function created on each render
3. Harder Debugging
- Indirect rendering logic
Modern Alternative
- Custom hooks
64. What are compound components?
Definition
Compound components are a pattern where multiple components work together as a single unit, sharing implicit state.
Example
<Tabs>
<Tabs.List />
<Tabs.Panel />
</Tabs>
Core Idea
- Parent manages state
- Children consume state implicitly
Benefits
- Flexible API
- Clean structure
- Declarative usage
65. What is the compound component pattern?
Definition
A design pattern where components are composed together and share state through context or internal logic.
Implementation
1. Parent Component
- Holds state
2. Child Components
- Access shared state
Example Concept
-
<Accordion>with<Accordion.Item>
Benefits
- Improves composability
- Reduces prop drilling
- Clean API design
Insight
Widely used in UI libraries
66. What is the container-presentational pattern?
Definition
A pattern that separates logic (container) from UI (presentational components).
Structure
1. Container Component
- Handles data fetching and logic
2. Presentational Component
- Handles UI rendering
Example
// Container
function UserContainer() {
const data = fetchUser();
return <UserView data={data} />;
}
Benefits
- Separation of concerns
- Reusability
- Easier testing
Modern Replacement
- Hooks reduce need for strict separation
67. What is inversion of control in React?
Definition
Inversion of Control (IoC) means delegating control of logic or behavior to another component.
Example
Instead of component deciding rendering:
<Modal renderContent={() => <Form />} />
Core Idea
- Parent provides behavior
- Child executes it
Benefits
- Flexibility
- Reusability
Insight
Used in render props and compound patterns
68. What is dependency inversion in component design?
Definition
Dependency Inversion Principle (DIP) states that high-level components should not depend on low-level implementations.
In React
Bad Example
fetch('/api/data');
Better
<DataService.fetchData();
Implementation
- Inject dependencies via props
- Use abstraction layers
Benefits
- Decoupling
- Easier testing
- Better scalability
69. What are React anti-patterns in large-scale apps?
Common Anti-patterns
1. Prop Drilling
- Passing props deeply
2. Overusing Context
- Causes re-renders
3. Large Components
- Hard to maintain
4. Direct DOM Manipulation
- Breaks React model
5. Uncontrolled Side Effects
- Logic inside render
6. Incorrect Key Usage
- Causes rendering bugs
7. Global Mutable State
- Leads to unpredictable behavior
Solution
- Use proper architecture
- Modularize components
- Use hooks and state management wisely
70. What is the difference between React.memo and useMemo?
Definitions
- React.memo: Higher-order component that memoizes a component
- useMemo: Hook that memoizes a computed value
Comparison
| Feature | React.memo | useMemo |
|---|---|---|
| Type | Component-level | Value-level |
| Purpose | Prevent re-render | Avoid recomputation |
| Usage | Wrap component | Inside component |
Example
React.memo
const MyComponent = React.memo((props) => {
return <div>{props.value}</div>;
});
useMemo
const value = useMemo(() => computeExpensive(), []);
Key Difference
- React.memo controls component rendering
- useMemo optimizes calculations inside components
Insight
They solve different performance problems but are often used together.
71. What are the differences between useCallback and useMemo?
Definitions
- useCallback: Memoizes a function
- useMemo: Memoizes a computed value
Comparison
| Feature | useCallback | useMemo |
|---|---|---|
| Returns | Function | Value |
| Purpose | Prevent function recreation | Avoid expensive recalculation |
| Use Case | Passing stable callbacks to children | Expensive computations |
Example
useCallback
const handleClick = useCallback(() => {
doSomething();
}, []);
useMemo
const result = useMemo(() => computeHeavy(), []);
Key Insight
-
useCallback(fn, deps)is essentially equivalent touseMemo(() => fn, deps) - Use when reference stability matters
72. What is useId and when should it be used?
Definition
useId is a hook in React that generates a unique, stable ID.
Purpose
- Useful for accessibility attributes
- Works correctly with server-side rendering
Example
const id = useId();
<label htmlFor={id}>Name</label>
<input id={id} />
When to Use
- Form inputs (label + input linking)
- Accessibility (ARIA attributes)
- SSR-safe IDs
Important Note
- Not for list keys
73. What is useTransition?
Definition
useTransition is a hook that lets you mark updates as non-urgent.
Core Idea
- Separate urgent vs non-urgent updates
Example
const [isPending, startTransition] = useTransition();
startTransition(() => {
setList(filterData());
});
Behavior
- Urgent updates (input typing) happen immediately
- Non-urgent updates (list rendering) are deferred
Benefits
- Keeps UI responsive
- Prevents blocking rendering
74. What is useDeferredValue?
Definition
useDeferredValue delays updating a value to avoid blocking the UI.
Core Idea
- Defer expensive updates
Example
const deferredValue = useDeferredValue(searchQuery);
Use Case
- Search input with heavy filtering
Difference from useTransition
-
useTransition→ defers state updates -
useDeferredValue→ defers value propagation
Benefit
- Smooth user interactions
75. What is useImperativeHandle?
Definition
useImperativeHandle customizes the instance value exposed to parent components via refs.
Usage Context
Used with forwardRef.
Example
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus()
}));
Purpose
- Expose controlled imperative APIs
- Hide internal implementation
Use Cases
- Custom input components
- Focus/scroll control
77. What is React Profiler?
Definition
React Profiler is a tool for measuring rendering performance in a React application.
Features
- Tracks render time
- Identifies slow components
- Shows commit durations
Tools
- React DevTools Profiler tab
-
<Profiler>API
Example
<Profiler id="App" onRender={callback}>
<App />
</Profiler>
Benefit
- Helps optimize performance
78. How do you measure component render performance?
Methods
1. React DevTools Profiler
- Analyze render timings
2. Profiler API
- Programmatic tracking
3. Console Timing
console.time('render');
// component logic
console.timeEnd('render');
4. Browser Performance Tools
- CPU and memory profiling
Metrics
- Render duration
- Commit time
- Re-render frequency
Insight
Focus on components with high render cost or frequent updates
79. What is render phase vs commit phase?
Definition
React updates UI in two phases.
1. Render Phase (Reconciliation)
- Calculates what changes are needed
- Can be paused/interrupted
2. Commit Phase
- Applies changes to DOM
- Runs effects
- Cannot be interrupted
Comparison
| Feature | Render Phase | Commit Phase |
|---|---|---|
| Purpose | Calculate changes | Apply changes |
| Interruptible | Yes | No |
| Side Effects | Not allowed | Allowed |
Insight
Render is pure computation, commit is actual DOM update
80. What is React reconciliation vs rendering?
Definitions
Reconciliation
- Process of comparing old and new Virtual DOM
Rendering
- Process of generating UI output
Relationship
- Reconciliation determines changes
- Rendering applies those changes
Flow
- State/props change
- Reconciliation runs (diffing)
- Rendering updates DOM
Key Difference
| Aspect | Reconciliation | Rendering |
|---|---|---|
| Role | Diffing algorithm | UI update |
| Focus | What changed | Apply changes |
Insight
Reconciliation is the decision-making step, rendering is execution
81. What is Shadow DOM vs Virtual DOM?
Definitions
Shadow DOM
- A browser feature that provides encapsulation of DOM and styles
- Used in Web Components
Virtual DOM
- An in-memory representation of the real DOM used by React
Comparison
| Feature | Shadow DOM | Virtual DOM |
|---|---|---|
| Purpose | Encapsulation | Performance optimization |
| Scope | Browser API | React internal mechanism |
| Styling | Isolated styles | Global CSS (by default) |
| Usage | Web Components | React rendering |
Insight
- Shadow DOM solves style isolation
- Virtual DOM solves efficient updates
82. How does React integrate with Web Workers?
Definition
Web Workers allow running JavaScript in a background thread separate from the main UI thread.
Why Use
- Offload heavy computations
- Prevent UI blocking
Integration Approach
1. Create Worker
const worker = new Worker('worker.js');
2. Communicate via postMessage
worker.postMessage(data);
worker.onmessage = (e) => setResult(e.data);
Use Cases
- Data processing
- Image manipulation
- Large computations
Limitations
- No direct DOM access
- Communication overhead
Insight
React handles UI, Workers handle heavy logic
83. How do you handle memory leaks in React apps?
Definition
Memory leaks occur when unused resources are not released, leading to increased memory usage.
Common Causes
1. Uncleaned subscriptions
2. Timers not cleared
3. Event listeners not removed
4. Async updates after unmount
Solutions
1. Cleanup in useEffect
useEffect(() => {
const id = setInterval(() => {}, 1000);
return () => clearInterval(id);
}, []);
2. Abort API calls
const controller = new AbortController();
3. Remove listeners
window.removeEventListener('resize', handler);
Best Practice
Always return a cleanup function in effects
84. What are stale closures in React hooks?
Definition
A stale closure occurs when a function captures outdated state or props.
Problem
Hook uses old values instead of current ones.
Example
useEffect(() => {
console.log(count); // stale value
}, []);
Cause
Missing dependencies in hook
Solution
- Add dependencies to array
- Use functional updates
setCount(prev => prev + 1);
Insight
Closures capture values at render time
85. What is dependency array bug and how do you avoid it?
Definition
Occurs when dependencies in hooks are incorrect or missing, causing bugs.
Problems
1. Missing dependencies
- Leads to stale data
2. Extra dependencies
- Causes unnecessary re-renders
Example
useEffect(() => {
fetchData(userId);
}, []); // missing dependency
Solutions
1. Follow ESLint rules
-
react-hooks/exhaustive-deps
2. Use stable references
-
useCallback,useMemo
3. Refactor logic
- Move logic inside effect
Insight
Dependency array must reflect all external values used
86. How do you test React components?
Approaches
1. Unit Testing
- Test individual components
2. Integration Testing
- Test interaction between components
3. End-to-End Testing
- Test full application flow
Tools
- Jest
- React Testing Library
Example
render(<Button />);
expect(screen.getByText('Click')).toBeInTheDocument();
Best Practices
- Test behavior, not implementation
- Focus on user interactions
87. What is Jest?
Definition
Jest is a JavaScript testing framework.
Features
- Zero configuration
- Snapshot testing
- Mocking support
- Fast execution
Example
test('adds numbers', () => {
expect(1 + 2).toBe(3);
});
Use Case
- Unit and integration testing
88. What is React Testing Library?
Definition
React Testing Library is a library for testing React components by focusing on user behavior.
Core Principle
- Test what users see and do
Example
screen.getByText('Submit');
Benefits
- Encourages best practices
- Avoids testing implementation details
89. What is shallow rendering?
Definition
Shallow rendering tests a component without rendering its child components.
Purpose
- Isolate component logic
Tools
- Enzyme (older approach)
Limitation
- Does not reflect real behavior
Insight
Less used now compared to React Testing Library
90. What is snapshot testing?
Definition
Snapshot testing compares component output with a saved snapshot.
Example
expect(tree).toMatchSnapshot();
Use Case
- Detect UI changes
Drawbacks
- Can become outdated
- Hard to maintain
Best Practice
Use sparingly for stable components
91. How do you test hooks?
Approaches
1. Using React Testing Library
- Test hooks via components
2. Using custom hook testing utilities
Example
const { result } = renderHook(() => useCounter());
expect(result.current.count).toBe(0);
Best Practices
- Test behavior, not implementation
- Simulate real usage
91. How do you test async behavior in React?
Definition
Testing async behavior means verifying how components behave when dealing with asynchronous operations like API calls, timers, or promises in a React app.
Common Scenarios
- Data fetching
- Delayed UI updates
- Loading states
Tools
- Jest
- React Testing Library
Techniques
1. waitFor
await waitFor(() => expect(screen.getByText('Data')).toBeInTheDocument());
2. findBy Queries
const element = await screen.findByText('Loaded');
3. Mock API Calls
- Replace real API with mock data
Best Practices
- Test loading → success → error states
- Avoid testing implementation details
92. What is mock server testing?
Definition
Mock server testing simulates backend APIs during testing.
Purpose
- Avoid real network calls
- Ensure predictable responses
Tools
- Mock Service Worker (MSW)
- Jest mocks
How It Works
- Intercepts network requests
- Returns predefined responses
Example
-
/api/usersreturns mock data
Benefits
- Faster tests
- Reliable and consistent results
93. What is contract testing in frontend?
Definition
Contract testing ensures that frontend and backend agree on API structure.
Core Idea
- Validate request/response format
Example
- Frontend expects
{ name: string } - Backend must return the same shape
Tools
- Pact
Benefits
- Prevents integration failures
- Ensures API consistency
94. What is end-to-end testing in React apps?
Definition
End-to-End (E2E) testing verifies the entire application flow from user perspective.
Scope
- UI + backend + network
Tools
- Cypress
- Playwright
Example
- User logs in → dashboard loads → action performed
Benefits
- High confidence in app behavior
- Detects real-world issues
Drawback
- Slower and more complex
95. How do you implement feature flags in React?
Definition
Feature flags allow enabling/disabling features dynamically without redeploying.
Implementation
1. Config-based
const isFeatureEnabled = true;
2. Remote Config
- Fetch flags from server
3. Libraries
- LaunchDarkly
Example
{isFeatureEnabled && <NewFeature />}
Benefits
- Safe feature rollout
- A/B testing
- Easy rollback
96. What is environment-based configuration in React?
Definition
Environment-based configuration means using different settings for different environments.
Environments
- Development
- Testing
- Production
Example
process.env.REACT_APP_API_URL
Use Cases
- API endpoints
- Feature toggles
- Debug settings
Benefit
- Flexible deployment
97. What is build-time vs runtime configuration?
Definitions
Build-time Configuration
- Set during build process
- Embedded into bundle
Runtime Configuration
- Loaded during app execution
Comparison
| Feature | Build-time | Runtime |
|---|---|---|
| When applied | Before deploy | After deploy |
| Flexibility | Low | High |
| Example | env variables | API config |
Insight
Runtime config is more flexible for dynamic environments
98. What is tree-shakeable code?
Definition
Tree-shakeable code is code structured in a way that allows unused parts to be removed during bundling.
Requirements
- ES modules (
import/export) - No side effects
Example
export const used = () => {};
export const unused = () => {};
Unused exports are removed.
Benefit
- Smaller bundle size
- Better performance
99. What is bundle analysis and how do you perform it?
Definition
Bundle analysis examines the size and composition of your JavaScript bundles.
Purpose
- Identify large dependencies
- Optimize performance
Tools
- Webpack Bundle Analyzer
- Vite analyzer
Process
1. Generate bundle stats
2. Visualize bundle
3. Identify heavy modules
4. Optimize (split/remove)
Outcome
- Reduced bundle size
- Faster load time
100. How do you secure React applications?
Key Areas
1. Prevent XSS (Cross-Site Scripting)
- Avoid
dangerouslySetInnerHTML
2. Secure API Calls
- Use HTTPS
- Validate tokens
3. Authentication & Authorization
- JWT, OAuth
4. Input Validation
- Sanitize user input
5. Secure Storage
- Avoid storing sensitive data in localStorage
6. Content Security Policy (CSP)
- Restrict resource loading
Insight
Frontend security is about minimizing attack surface
101. How does JSX prevent injection attacks?
Definition
JSX automatically escapes values to prevent injection attacks.
How It Works
- Converts values to safe strings
- Prevents execution of malicious scripts
Example
const name = "<script>alert(1)</script>";
<div>{name}</div>
Output is rendered as text, not executed.
Exception
<div dangerouslySetInnerHTML={{ __html: html }} />
- Bypasses protection
Best Practice
- Avoid raw HTML injection
- Sanitize input when necessary