๐ React Component Lifecycle โ Complete Theory Guide
1. ๐ง Introduction
๐น What is Component Lifecycle?
The Component Lifecycle in React refers to the series of phases a component goes through from:Creation โ Updating โ Removal (Unmounting)Each phase provides specific methods (class components) or hooks (functional components) that allow you to control behavior at different stages.
๐น Why is it Important?
Understanding lifecycle is critical because it allows you to:- Control when side effects run
- Manage API calls & subscriptions
- Optimize performance
- Prevent memory leaks
- Handle DOM interactions safely
๐น When & Why Do We Use It?
You use lifecycle logic when:- Fetching data from APIs
- Setting up event listeners
- Working with timers (setInterval / setTimeout)
- Updating DOM manually
- Cleaning up resources (subscriptions, listeners)
2. โ๏ธ Concepts / Internal Workings
๐น Lifecycle Phases
React lifecycle is divided into 3 main phases:1๏ธโฃ Mounting Phase (Component Creation)
When a component is created and inserted into the DOM. Class Methods:constructor()render()componentDidMount()
useEffect(() => {}, [])
2๏ธโฃ Updating Phase (Re-rendering)
Occurs when:- Props change
- State changes
- Parent re-renders
shouldComponentUpdate()render()componentDidUpdate()
useEffect(() => {}, [dependencies])
3๏ธโฃ Unmounting Phase (Component Removal)
When a component is removed from the DOM. Class Method:componentWillUnmount()
- Cleanup function in
useEffect
๐น Internal Working in React
React lifecycle is tightly coupled with:โก Reconciliation Algorithm
- React compares previous and next Virtual DOM
- Determines minimal updates
- Triggers lifecycle accordingly
โก Render vs Commit Phase
React internally splits work into:๐งฉ Render Phase (Pure Calculation)
- Calculates what should change
- Can be paused or restarted
๐งฉ Commit Phase (DOM Update)
- Applies changes to DOM
-
Runs lifecycle methods like:
componentDidMountcomponentDidUpdateuseEffect
๐น Relationship with Other React Features
โ๏ธ State
- State updates trigger lifecycle (re-renders)
โ๏ธ Props
- Prop changes cause update phase
โ๏ธ Hooks
- Replace lifecycle methods in functional components
โ๏ธ Strict Mode
- May run lifecycle twice (dev only) to detect bugs
3. ๐ป Syntax & Examples
๐น Class Component Lifecycle Example
๐น Functional Component (Modern Approach)
๐น API Call Example (Real-world)
๐น Cleanup Example (Important)
๐น Conditional Effect Example
4. โ ๏ธ Edge Cases / Common Mistakes
โ Infinite Loops in useEffect
- Use conditions or proper dependencies
โ Missing Dependency Array
โ Incorrect Cleanup
โ Using componentDidMount Logic Incorrectly
- In hooks, forgetting
[]leads to repeated execution
โ State Updates in Render (Class)
โ Stale Closures
- Use refs or include dependency
โ Strict Mode Double Execution
useEffectmay run twice in development- This is intentional for detecting side effects
5. โ Best Practices
๐น 1. Prefer Functional Components + Hooks
- Hooks are more readable and composable
- Avoid legacy lifecycle unless maintaining old code
๐น 2. Keep Effects Focused
๐ One effect = one responsibility๐น 3. Always Handle Cleanup
- Timers
- Event listeners
- Subscriptions
๐น 4. Optimize Re-renders
-
Use:
React.memouseMemouseCallback
๐น 5. Avoid Unnecessary Effects
๐ If you can compute something during render, donโt useuseEffect
๐น 6. Use Dependency Array Carefully
- Include all dependencies
- Follow ESLint rule:
react-hooks/exhaustive-deps
๐น 7. Avoid Heavy Work in Effects
- Offload heavy tasks
- Use debouncing / throttling
๐น 8. Handle Async Safely
๐น 9. Think in Terms of Synchronization
React lifecycle is not about โstepsโ โ itโs about:Syncing UI with state & external systems
๐น 10. Understand Timing
๐ Final Summary
- Lifecycle = Mount โ Update โ Unmount
- Hooks replace class lifecycle methods
useEffectis the core tool for lifecycle management- Correct dependency management is critical
- Cleanup prevents memory leaks
- Think in terms of data flow & synchronization, not just lifecycle steps
๐ง React Component Lifecycle โ Senior-Level Interview Questions
1. What is the real purpose of the component lifecycle in modern React, beyond the basic definition?
โ Strong Answer
At a senior level, lifecycle is not about โmount/update/unmountโ โ itโs about:Synchronizing UI with external systems and side effectsReact is declarative, but:
- APIs
- DOM APIs
- subscriptions
- timers
- start synchronization (mount / dependency change)
- update synchronization (state/prop changes)
- stop synchronization (cleanup)
๐ก Why this matters
- Prevents memory leaks
- Avoids race conditions
- Ensures UI consistency
โ๏ธ Trade-off
- Overusing lifecycle โ unnecessary complexity
- Underusing โ bugs and leaks
2. How does React internally decide when to trigger lifecycle methods or hooks?
โ Strong Answer
Lifecycle is driven by Reactโs reconciliation process:- React builds a new Virtual DOM
- Compares it with the previous one (diffing)
- Determines minimal changes
-
During commit phase:
- Runs lifecycle methods / effects
๐ Key Insight
React has two phases:
๐
useEffect runs after commit
โ ๏ธ Why it matters
- Effects should not rely on render timing
- DOM is guaranteed to be updated when
useEffectruns
3. Why does useEffect run after render instead of before?
โ Strong Answer
Because React prioritizes UI consistency and non-blocking rendering If effects ran before:- They could block rendering
- UI would feel slow
- React renders UI first
- Then runs effects asynchronously
๐ Comparison
๐ก Example
โ๏ธ Trade-off
useEffect: better performanceuseLayoutEffect: needed for DOM measurement but can block rendering
4. Why does React Strict Mode intentionally double-invoke lifecycle logic?
โ Strong Answer
In development, React Strict Mode intentionally:- Mounts โ unmounts โ mounts again
- Side effects that arenโt idempotent
- Missing cleanup logic
๐ก Example Problem
๐ Why this exists
React prepares for:- Concurrent rendering
- Interruptible rendering
โ๏ธ Trade-off
- Confusing for beginners
- Extremely valuable for catching bugs early
5. What are the risks of treating useEffect as a replacement for all lifecycle logic?
โ Strong Answer
Common misconception:โPut everything in useEffectโ
โ Problems
-
Overuse
- Leads to unnecessary re-renders
- Derived state misuse
- Tight coupling of logic
โ Better Approach
-
Use effects only for:
- External systems
- Side effects
๐ก Principle
โIf it can be calculated during render, donโt use useEffect.โ
6. Explain the concept of stale closures in lifecycle logic.
โ Strong Answer
Closures capture values at the time of render, not live values.โ Problem
๐ Why it happens
- Effect runs once
- Closure captures initial
count
โ Solutions
1. Add dependency
2. Use ref
โ๏ธ Trade-off
- Adding dependencies โ more re-renders
- Using refs โ more manual control
7. Why is cleanup in lifecycle critical, and what happens if you skip it?
โ Strong Answer
Cleanup prevents:- Memory leaks
- Duplicate subscriptions
- Unexpected behavior
โ Example
โ Correct
๐ก Real-world Impact
- Performance degradation
- Hard-to-debug bugs
8. How does dependency array affect lifecycle behavior internally?
โ Strong Answer
Dependency array controls when React re-runs the effect. React:- Compares previous dependencies with new ones (shallow comparison)
- If changed โ runs cleanup โ runs effect again
๐ Example
โ ๏ธ Pitfall
Objects/functions always change reference:โ Solution
useMemouseCallback
9. What is the difference between useEffect and useLayoutEffect in real-world scenarios?
โ Strong Answer
๐ก Use Cases
useEffect
- API calls
- Logging
- subscriptions
useLayoutEffect
- Measuring DOM
- Sync layout changes
โ ๏ธ Example
โ๏ธ Trade-off
useLayoutEffectcan hurt performance- Should be used sparingly
10. How does React handle lifecycle during re-renders caused by parent components?
โ Strong Answer
When parent re-renders:- Child components also re-render by default
๐ Why?
React does not automatically memoize componentsโ Optimization
โ๏ธ Trade-off
- Memoization adds complexity
- Useful only when render is expensive
11. Why is it dangerous to update state unconditionally inside lifecycle logic?
โ Strong Answer
It causes infinite render loopsโ Example
๐ Why?
- State update โ re-render โ effect runs โ repeat
โ Fix
- Add condition
- Use functional updates
12. Explain how async operations interact with lifecycle and potential issues.
โ Strong Answer
Async operations can complete:- After component unmount
- In different order (race conditions)
โ Problem
โ ๏ธ Issues
- Setting state on unmounted component
- Data inconsistency
โ Solution
13. What design trade-offs led React to move from class lifecycle methods to hooks?
โ Strong Answer
โ Problems with class lifecycle
- Logic scattered across methods
- Hard to reuse logic
- Complex mental model
โ Hooks solve:
- Co-locating logic
- Reusability (custom hooks)
- Simpler composition
๐ก Example
Before:โ๏ธ Trade-off
- Hooks introduce dependency complexity
- Learning curve for closures
14. How does React ensure consistency between UI and effects in concurrent rendering?
โ Strong Answer
React ensures:- Effects only run after committed UI
- Effects from abandoned renders are discarded
๐ Why important?
- Prevents inconsistent state
- Avoids running effects for UI that never appeared
15. When should you NOT use lifecycle logic at all?
โ Strong Answer
Avoid lifecycle when:- Computing derived data
- Formatting values
- Filtering lists
โ Bad
โ Good
๐ก Principle
Lifecycle is for side effects, not data transformation
๐ Final Takeaway
At a senior level:- Lifecycle is about synchronization, not steps
-
Effects must be:
- intentional
- minimal
- predictable
-
Misusing lifecycle leads to:
- performance issues
- subtle bugs
- hard-to-debug behavior
๐ง React Component Lifecycle โ Advanced MCQs (Senior Level)
1. When does useEffect actually execute in React?
Question:
Given a component render, when is useEffect guaranteed to run?
A. Before render begins
B. After render but before DOM updates
C. After DOM updates are committed to the screen
D. During reconciliation phase
โ
Correct Answer: C
โ Explanation
-
useEffectruns after the commit phase, meaning:- DOM is updated
- Browser has painted (usually)
โ Why others are wrong
- A: Effects never run before render
- B: Thatโs
useLayoutEffect - D: Reconciliation is pure calculation; effects donโt run there
2. What happens if you omit the dependency array in useEffect?
A. Runs only once on mount
B. Runs on every render
C. Runs only when state changes
D. Runs only on unmount
โ
Correct Answer: B
โ Explanation
Without dependencies, React assumes:โRun after every renderโ
โ Why others are wrong
- A: Only happens with
[] - C: Not limited to state changes
- D: Cleanup runs on unmount, not effect
3. What is the behavior of this code in Strict Mode (development)?
โ Explanation
In React Strict Mode:- React mounts โ unmounts โ mounts again
- Helps detect unsafe side effects
โ Why others are wrong
- A: True only in production
- C: No loop here
- D: Opposite of reality
4. What is the biggest issue with this code?
โ Explanation
countchanges โ effect runs โ updates state โ repeat
โ Why others are wrong
- A: Definitely problematic
- B: No leak here
- D: Closure is fresh due to dependency
5. What happens if an object is used as a dependency?
โ Explanation
- React does shallow comparison
- New object reference each render โ effect runs
โ Why others are wrong
- A: Only for stable reference
- B: No deep comparison
- D: Valid code
6. Which scenario requires useLayoutEffect instead of useEffect?
A. Fetching API data
B. Logging analytics
C. Measuring DOM size before paint
D. Setting timers
โ
Correct Answer: C
โ Explanation
useLayoutEffectruns before paint- Needed for layout measurements to avoid flicker
โ Why others are wrong
- A/B/D: Non-blocking tasks โ useEffect preferred
7. What happens if cleanup is missing in an effect with event listeners?
A. Nothing B. Event listeners stack up C. React auto-cleans them D. Component crashes immediately โ Correct Answer: Bโ Explanation
- Each mount adds a new listener
- Leads to duplicate handlers
โ Why others are wrong
- A: Incorrect, causes bugs
- C: React does not auto-clean external effects
- D: No immediate crash
8. What is the key problem in this code?
โ Explanation
- Stale closure โ logs old
count - Memory leak โ interval never cleared
โ Why others are wrong
- A: No loop triggered
- B/C: Both issues exist
9. What ensures effects from abandoned renders donโt execute?
A. Dependency array B. Cleanup function C. Commit phase control D. Memoization โ Correct Answer: Cโ Explanation
- React only runs effects for committed renders
- Discards interrupted renders
โ Why others are wrong
- A/B/D: Not responsible for this guarantee
10. What happens when a parent re-renders but props donโt change?
A. Child never re-renders B. Child always re-renders C. Child re-renders only in Strict Mode D. Child re-renders only if state changes โ Correct Answer: Bโ Explanation
- React re-renders children by default
โ Why others are wrong
- A: Needs
React.memo - C/D: Incorrect assumptions
11. Which is the correct cleanup timing?
A. Before next effect runs B. After component unmounts only C. Before render phase D. After every render โ Correct Answer: Aโ Explanation
Cleanup runs:- Before next effect
- On unmount
โ Why others are wrong
- B: Not only unmount
- C/D: Incorrect timing
12. What is the issue with derived state in useEffect?
A. No issue
B. Causes unnecessary re-renders
C. Breaks React rules
D. Causes memory leaks
โ
Correct Answer: B
โ Explanation
Derived state:- Can be computed during render
- Using effect โ extra render cycle
โ Why others are wrong
- A: Suboptimal pattern
- C: Not illegal
- D: No leak
13. What is the behavior of useEffect with multiple dependencies?
A. Runs if all change
B. Runs if any change
C. Runs only on mount
D. Runs randomly
โ
Correct Answer: B
โ Explanation
- Any dependency change triggers effect
โ Why others are wrong
- A: Not required for all
- C/D: Incorrect
14. Why should heavy computations be avoided inside effects?
A. Effects run before render B. Blocks UI thread C. Causes memory leaks D. Prevents cleanup โ Correct Answer: Bโ Explanation
- JS is single-threaded
- Heavy work blocks responsiveness
โ Why others are wrong
- A: Effects run after render
- C/D: Not directly related
15. What happens if you forget dependencies in async effect?
A. Nothing B. Runs only once C. May use stale data D. Crashes app โ Correct Answer: Cโ Explanation
- Missing dependencies โ stale values captured
โ Why others are wrong
- A/B/D: Misrepresent behavior
16. What is the correct pattern to prevent state updates after unmount?
A. Try/catch B. isMounted flag or AbortController C. setTimeout D. useMemo โ Correct Answer: Bโ Explanation
Prevents:- Updating unmounted component
- Race conditions
โ Why others are wrong
- A: Not relevant
- C/D: No effect
17. Why does React discourage side effects during render?
A. Slows down browser B. Breaks purity of render C. Causes memory leaks D. Prevents updates โ Correct Answer: Bโ Explanation
Render must be:- Pure
- Predictable
- Side-effect free
โ Why others are wrong
- A/C/D: Secondary or incorrect reasons
18. What is the impact of React.memo on lifecycle?
A. Skips lifecycle completely
B. Skips re-render if props unchanged
C. Prevents useEffect from running
D. Disables state updates
โ
Correct Answer: B
โ Explanation
- Memo prevents unnecessary re-renders
- Lifecycle tied to render โ skipped if not re-rendered
โ Why others are wrong
- A: Lifecycle still exists
- C/D: Incorrect behavior
๐ Final Insight
These questions test whether a developer understands:- Lifecycle = synchronization model
- Effects = controlled side effects
- React = render โ commit โ effect
- Avoid misuse of lifecycle
- Optimize effects
- Understand internal timing deeply
๐ง React Component Lifecycle โ Real-World Coding Problems (Senior Level)
1. Auto-Save Form with Debounce
๐งฉ Problem
Build a form that auto-saves user input after 500ms of inactivity.โ๏ธ Constraints
- Avoid API calls on every keystroke
- Cancel previous pending save if user types again
- Save only latest value
โ Expected Behavior
- User types โ waits โ API called once
- Rapid typing โ only last value saved
โ ๏ธ Edge Cases
- Component unmount before timeout
- Rapid typing
- Stale values
๐ก Solution Approach
๐ง Explanation
- Cleanup cancels previous timer
- Prevents multiple API calls
- Uses lifecycle to sync input โ API
2. Prevent State Update After Unmount (API Call)
๐งฉ Problem
Fetch data from API but prevent updating state if component unmounts.โ๏ธ Constraints
- Avoid memory leaks
- Handle slow API
โ ๏ธ Edge Cases
- Component unmounts before response
- Multiple requests
๐ก Solution
๐ง Explanation
- Lifecycle cleanup prevents unsafe updates
3. Window Resize Listener
๐งฉ Problem
Track window width and update UI.โ๏ธ Constraints
- Add listener once
- Remove on unmount
โ ๏ธ Edge Cases
- Multiple mounts
- Memory leaks
๐ก Solution
๐ง Explanation
- Lifecycle manages subscription lifecycle
4. Polling API Every 5 Seconds
๐งฉ Problem
Fetch updated data every 5 seconds.โ๏ธ Constraints
- Stop polling on unmount
- Avoid multiple intervals
๐ก Solution
โ ๏ธ Edge Cases
- Interval stacking
- Component unmount
5. Sync Document Title
๐งฉ Problem
Updatedocument.title based on state.
๐ก Solution
๐ง Insight
- Side effect tied to state
6. Abort Fetch on Dependency Change
๐งฉ Problem
Cancel previous API request when search query changes.๐ก Solution
โ ๏ธ Edge Cases
- Race conditions
- Rapid query changes
7. Detect First Render Only
๐งฉ Problem
Run logic only on first render.๐ก Solution
โ ๏ธ Twist
Avoid misusing for derived state8. Track Previous State Value
๐งฉ Problem
Compare current and previous value of a variable.๐ก Solution
๐ง Insight
- Lifecycle helps track changes over time
9. Prevent Infinite Loop in Effect
๐งฉ Problem
Fix an effect causing infinite re-renders.๐ก Solution
๐ง Insight
- Add conditions to break loops
10. Lazy Load Component on Visibility
๐งฉ Problem
Load data only when component enters viewport.๐ก Solution
โ ๏ธ Edge Cases
- Multiple triggers
- Cleanup
11. Debounced Search with API Cancellation
๐งฉ Problem
Combine debounce + cancel previous request.๐ก Solution
- Use both
setTimeout+AbortController
๐ง Insight
- Multiple lifecycle concerns combined
12. Sync LocalStorage with State
๐งฉ Problem
Persist state to localStorage.๐ก Solution
โ ๏ธ Edge Cases
- Serialization errors
- Large data
13. Custom Hook: useInterval
๐งฉ Problem
Create reusable interval hook.๐ก Solution
๐ง Insight
- Lifecycle abstraction
14. Avoid Stale Closure in Interval
๐งฉ Problem
Fix stale state inside interval.๐ก Solution
๐ง Insight
- Functional updates avoid stale closure
15. Conditional Effect Execution
๐งฉ Problem
Run effect only when a condition is met.๐ก Solution
๐ง Insight
- Guard conditions inside effect
16. Multi-Effect Separation
๐งฉ Problem
Split unrelated logic into separate effects.๐ก Solution
๐ง Insight
- Improves maintainability
17. Handle Rapid Prop Changes
๐งฉ Problem
Prop changes quickly โ avoid race conditions.๐ก Solution
- Use AbortController or tracking ID
๐ง Insight
- Lifecycle must handle async ordering
18. Animate on Mount
๐งฉ Problem
Trigger animation when component mounts.๐ก Solution
โ ๏ธ Edge Case
- Strict Mode double-trigger
19. Global Event Bus Subscription
๐งฉ Problem
Subscribe to external event system.๐ก Solution
๐ง Insight
- Lifecycle manages external systems
๐ Final Thought
These problems test:- Lifecycle as synchronization
- Managing side effects safely
- Handling async + cleanup + performance
๐ง React Component Lifecycle โ Debugging Challenges (Senior Code Review)
1. ๐ฅ Infinite Re-render Loop (Hidden)
โ Whatโs Wrong
- State update depends on
filters, but also updates it โ loop
๐คฏ Why It Happens
- New object reference each time โ dependency always โchangesโ
โ Fix
๐ก Best Practice
- Avoid setting state from itself inside dependency-based effects
- Use functional updates or rethink logic
2. ๐งจ Stale Closure in Interval
โ Whatโs Wrong
countis always initial value
๐คฏ Why
- Closure captures value at mount
โ Fix
๐ก Best Practice
- Use functional updates for async loops
3. โ ๏ธ Memory Leak with Event Listener
โ Whatโs Wrong
- No cleanup โ multiple listeners over time
๐คฏ Why
- Component unmount/remount adds new listener each time
โ Fix
๐ก Best Practice
- Always clean up subscriptions
4. ๐ Incorrect Dependency (Silent Bug)
โ Whatโs Wrong
- Missing
userIddependency
๐คฏ Why
- Effect runs only once โ stale data if
userIdchanges
โ Fix
๐ก Best Practice
- Follow exhaustive-deps rule
5. ๐ง Derived State Anti-pattern
โ Whatโs Wrong
- Unnecessary state + effect
๐คฏ Why
- Causes extra render cycle
โ Fix
๐ก Best Practice
- Avoid derived state in effects
6. โก Over-fetching Due to Object Dependency
โ Whatโs Wrong
filtersrecreated โ effect runs unnecessarily
๐คฏ Why
- Shallow comparison detects new reference
โ Fix
๐ก Best Practice
- Stabilize dependencies with
useMemo
7. ๐งจ Race Condition in API Calls
โ Whatโs Wrong
- Old response may overwrite new one
๐คฏ Why
- Async order is not guaranteed
โ Fix
๐ก Best Practice
- Always cancel previous async work
8. ๐งฉ Missing Cleanup in setTimeout
โ Whatโs Wrong
- Timeout runs even after unmount
๐คฏ Why
- No cleanup
โ Fix
๐ก Best Practice
- Cleanup all timers
9. โ ๏ธ useEffect Doing Too Much
โ Whatโs Wrong
- Multiple concerns in one effect
๐คฏ Why
- Hard to maintain, debug, and optimize
โ Fix
๐ก Best Practice
- One responsibility per effect
10. ๐ Infinite Loop via Function Dependency
โ Whatโs Wrong
fetchDatarecreated every render
๐คฏ Why
- Function identity changes
โ Fix
๐ก Best Practice
- Stabilize functions with
useCallback
11. ๐ง Misuse of useLayoutEffect
โ Whatโs Wrong
- Blocking render unnecessarily
๐คฏ Why
- useLayoutEffect runs before paint
โ Fix
๐ก Best Practice
- Use layout effect only for DOM measurement
12. ๐งจ Duplicate API Calls in Strict Mode
โ Whatโs Wrong
- Runs twice in dev
๐คฏ Why
- React Strict Mode double-invokes
โ Fix
๐ก Best Practice
- Write idempotent effects
13. โ ๏ธ Missing Dependency in Callback
โ Whatโs Wrong
countis stale
๐คฏ Why
- Dependency missing
โ Fix
๐ก Best Practice
- Include all dependencies
14. ๐ State Update After Unmount
โ Whatโs Wrong
- Updates after unmount
๐คฏ Why
- Async completes late
โ Fix
๐ก Best Practice
- Guard async updates
15. โก Performance Issue from Frequent Effects
โ Whatโs Wrong
- Runs every render
๐คฏ Why
- No dependency array
โ Fix
๐ก Best Practice
- Control execution frequency
16. ๐งฉ Incorrect Cleanup Order Assumption
โ Misunderstanding
- Developers expect cleanup after new effect
๐คฏ Reality
- Cleanup runs before next effect
๐ก Best Practice
-
Understand lifecycle order:
cleanup โ new effect
๐ Final Insight
These bugs represent real production issues:- Race conditions
- Stale closures
- Dependency mismanagement
- Memory leaks
- Performance regressions
- Think in data flow + synchronization
- Treat lifecycle as controlled side-effect system
๐ง React Component Lifecycle โ Real-World Machine Coding Problems (Senior Architect Level)
1. ๐งพ Real-Time Search with Debounce + Cancellation
๐ Requirements
- Search input with API results
- Debounce input (300ms)
- Cancel previous request on new input
- Show loading + error states
๐ฅ๏ธ UI Behavior
- Typing โ delayed API call
- Fast typing โ only latest request processed
- Show spinner while fetching
๐ State / Data Flow
-
queryโ triggers effect -
Effect handles:
- debounce timer
- API call
- cleanup (abort)
โ ๏ธ Edge Cases
- Empty input
- Rapid typing
- Slow API responses (race conditions)
โก Performance
- Avoid unnecessary API calls
- Prevent stale data overwrite
๐๏ธ Suggested Architecture
useEffectfor debounce + fetchAbortControllerfor cancellation- Separate UI and data logic (custom hook)
๐ง Approach
- Store query in state
- Debounce with
setTimeout - Abort previous fetch
- Cleanup on re-run
2. ๐ก Live Stock Price Dashboard
๐ Requirements
- Fetch stock prices every 2 seconds
- Pause/resume updates
- Highlight changed values
๐ฅ๏ธ UI Behavior
- Auto-updating prices
- Button to pause updates
๐ State Flow
- Interval lifecycle controls polling
- Track previous prices for diffing
โ ๏ธ Edge Cases
- Multiple intervals
- Component unmount
- Network failure
โก Performance
- Avoid unnecessary re-renders
- Batch updates
๐๏ธ Architecture
useEffectwith intervaluseReffor previous values
๐ง Approach
- Start interval on mount
- Clear interval on unmount
- Compare previous vs current prices
3. ๐ฆ Infinite Scroll Feed (Like Instagram)
๐ Requirements
- Load posts when scrolling near bottom
- Prevent duplicate fetches
- Maintain scroll position
๐ฅ๏ธ UI Behavior
- Smooth loading
- Loading indicator at bottom
๐ State Flow
pagestate triggers API- Observer detects viewport
โ ๏ธ Edge Cases
- Fast scrolling
- Duplicate API calls
- End of data
โก Performance
- Use IntersectionObserver
- Avoid scroll event listeners
๐๏ธ Architecture
- Custom hook for observer
- Effect handles fetching
๐ง Approach
- Observe sentinel element
- Fetch next page
- Cleanup observer
4. ๐ Notification System (Real-Time)
๐ Requirements
- Subscribe to WebSocket
- Display incoming notifications
- Clean up on unmount
๐ State Flow
- WebSocket โ pushes data โ updates state
โ ๏ธ Edge Cases
- Reconnect logic
- Duplicate messages
- Memory leaks
โก Performance
- Avoid re-subscribing unnecessarily
๐๏ธ Architecture
- Effect manages socket lifecycle
- Separate hook for subscription
๐ง Approach
- Connect socket on mount
- Listen for messages
- Disconnect on unmount
5. ๐ง Form Auto-Save Draft (Google Docs Style)
๐ Requirements
- Save draft every 2 seconds if changes exist
- Show โSavingโฆโ and โSavedโ
โ ๏ธ Edge Cases
- Rapid typing
- Offline mode
- API failure
โก Performance
- Avoid redundant saves
๐๏ธ Architecture
- Compare current vs last saved state
- Interval-based effect
๐ง Approach
- Track dirty state
- Run interval
- Save only if changed
6. ๐ฅ Video Player with Lifecycle Sync
๐ Requirements
- Sync play/pause state with UI
- Pause video on unmount
โ ๏ธ Edge Cases
- Tab switch
- Component remount
๐๏ธ Architecture
useEffectto sync DOM video element
๐ง Approach
- Use ref
- Control video via effect
7. ๐ Multi-Tab Sync (localStorage)
๐ Requirements
- Sync state across browser tabs
๐ State Flow
storageevent listener
โ ๏ธ Edge Cases
- Infinite update loop
- Same-tab updates
๐๏ธ Architecture
- Effect adds storage listener
๐ง Approach
- Listen for storage changes
- Update state conditionally
8. ๐ Geolocation Tracker
๐ Requirements
- Track user location in real-time
- Stop tracking on unmount
โ ๏ธ Edge Cases
- Permission denied
- High-frequency updates
๐๏ธ Architecture
- Effect manages
navigator.geolocation.watchPosition
๐ง Approach
- Subscribe on mount
- Clear watch on unmount
9. ๐งพ Dynamic Form Builder
๐ Requirements
- Add/remove fields dynamically
- Validate on change
โ ๏ธ Edge Cases
- Validation loops
- stale state
๐๏ธ Architecture
- Separate validation effect
๐ง Approach
- Store form schema
- Trigger validation effect
10. ๐ Retry Failed API with Backoff
๐ Requirements
- Retry API up to 3 times
- Exponential delay
โ ๏ธ Edge Cases
- Infinite retries
- component unmount
๐๏ธ Architecture
- Effect + recursive retry
๐ง Approach
- Track retry count
- Cleanup pending retries
11. ๐ง Undo/Redo State System
๐ Requirements
- Maintain history
- Undo/redo actions
โ ๏ธ Edge Cases
- Memory growth
- state sync
๐๏ธ Architecture
- Use reducer + effect for side effects
๐ง Approach
- Store history stack
- Update on state change
12. ๐งพ Smart Table with Server Pagination
๐ Requirements
- Fetch data on page change
- Cache previous pages
โ ๏ธ Edge Cases
- duplicate requests
- stale data
๐๏ธ Architecture
- Cache layer + effect
๐ง Approach
- Store cache in ref
- fetch only if not cached
13. ๐งช A/B Testing Variant Loader
๐ Requirements
- Fetch variant config
- Apply experiment
โ ๏ธ Edge Cases
- flicker before load
- race conditions
๐๏ธ Architecture
- blocking vs non-blocking effect
๐ง Approach
- load config early
- fallback UI
14. ๐งญ Route Change Analytics Tracker
๐ Requirements
- Track page views on route change
โ ๏ธ Edge Cases
- duplicate tracking
- fast navigation
๐๏ธ Architecture
- Effect watching route
๐ง Approach
- debounce tracking
- track only meaningful changes
15. ๐ Live Chart with Streaming Data
๐ Requirements
- Update chart in real-time
- limit data points
โ ๏ธ Edge Cases
- memory overflow
- UI lag
๐๏ธ Architecture
- interval + sliding window
๐ง Approach
- push new data
- remove old data
16. ๐ง Feature Flag System
๐ Requirements
- Dynamically enable features
โ ๏ธ Edge Cases
- flicker
- stale config
๐๏ธ Architecture
- global state + effect
๐ง Approach
- fetch config
- conditionally render
17. ๐ Session Timeout Handler
๐ Requirements
- Auto logout after inactivity
โ ๏ธ Edge Cases
- multiple timers
- background tab
๐๏ธ Architecture
- event listeners + timer
๐ง Approach
- reset timer on activity
- cleanup listeners
18. ๐ฅ File Upload with Progress
๐ Requirements
- Show upload progress
- cancel upload
โ ๏ธ Edge Cases
- cancel mid-upload
- retry
๐๏ธ Architecture
- effect manages upload lifecycle
๐ง Approach
- track progress
- abort controller
19. ๐ง Virtualized List (Performance)
๐ Requirements
- Render only visible items
โ ๏ธ Edge Cases
- scroll jump
- dynamic height
๐๏ธ Architecture
- effect handles scroll events
๐ง Approach
- calculate visible range
- render subset
๐ Final Insight
These problems test:- Lifecycle as synchronization engine
-
Managing:
- async work
- subscriptions
- performance
- cleanup
- Designing scalable architecture
๐ง React Component Lifecycle โ FAANG-Level Interview Questions
1. Lifecycle vs Synchronization Model
โ Question
React docs say โthink in effects, not lifecycle.โ What does that actually mean?๐ Follow-up
- When would lifecycle thinking break down?
- Can you give a real-world example?
โ Strong Answer
Lifecycle is traditionally seen as:mount โ update โ unmountBut modern React reframes it as:
synchronizing UI with external systemsExample:
- Not โon mountโ
- But โwhenever roomId changes, sync connectionโ
โ Weak Answer
โLifecycle is just useEffect replacing componentDidMountโ ๐ Fails because:- Misses conceptual shift
- No understanding of synchronization model
2. Effect Timing & Rendering Phases
โ Question
Explain how lifecycle hooks align with Reactโs render and commit phases.๐ Follow-up
- Why can effects not run during render?
- What happens in concurrent rendering?
โ Strong Answer
- Render phase: pure calculation (can be interrupted)
- Commit phase: DOM updates + effects run
โ Weak Answer
โuseEffect runs after renderโ ๐ Too shallow; doesnโt explain phases or concurrency3. Designing a Data Fetching Strategy
โ Question
How would you design data fetching in a component with changing inputs?๐ Follow-up
- How do you avoid race conditions?
- How do you handle caching?
โ Strong Answer
- Use
useEffectwith dependencies - Cancel previous requests (AbortController)
- Handle stale responses
- Possibly move to data layer (React Query)
โ Weak Answer
โCall fetch inside useEffectโ ๐ Ignores:- cancellation
- caching
- race conditions
4. Debugging Infinite Effect Loops
โ Question
You see an effect causing repeated API calls. How do you debug it?๐ Follow-up
- What tools or logs would you use?
- How do dependencies play a role?
โ Strong Answer
- Check dependency array
-
Look for:
- object/function dependencies
- state updates inside effect
- Use console + React DevTools
โ Weak Answer
โJust add []โ ๐ Dangerous blanket fix5. Stale Closures in Production
โ Question
Explain a real-world bug caused by stale closures and how to fix it.๐ Follow-up
- Why doesnโt React auto-fix this?
- When should you use refs vs dependencies?
โ Strong Answer
- Closure captures old values
- Example: interval logging old state
-
Fix via:
- dependencies OR
- functional updates OR
- refs
โ Weak Answer
โJust add dependencyโ ๐ Not always correct (can cause loops)6. Strict Mode Behavior
โ Question
Why does React double-run effects in development?๐ Follow-up
- What kind of bugs does it expose?
- Should you โfixโ double execution?
โ Strong Answer
- React Strict Mode simulates mount/unmount cycles
- Detects unsafe side effects
- Ensures idempotent effects
โ Weak Answer
โItโs a bug in Reactโ ๐ Shows lack of understanding7. Choosing Between useEffect vs useLayoutEffect
โ Question
When would you chooseuseLayoutEffect over useEffect?
๐ Follow-up
- What performance risks exist?
- Give a real UI bug example
โ Strong Answer
-
useLayoutEffect for:
- DOM measurement
- preventing flicker
- Avoid for async work
โ Weak Answer
โThey are the sameโ ๐ Incorrect and risky8. Derived State vs Effects
โ Question
When is usinguseEffect for derived state a bad idea?
๐ Follow-up
- Whatโs the cost of doing it wrong?
โ Strong Answer
- Causes extra render cycle
- Should compute during render instead
โ Weak Answer
โIt works fineโ ๐ Ignores performance + correctness9. Designing Reusable Lifecycle Logic
โ Question
How do you abstract lifecycle logic across components?๐ Follow-up
- Trade-offs of custom hooks?
- When NOT to abstract?
โ Strong Answer
- Use custom hooks
- Encapsulate side effects
โ Weak Answer
โCopy-paste useEffectโ10. Handling Async Side Effects Safely
โ Question
How do you prevent updating state after unmount?๐ Follow-up
- How does AbortController compare to flags?
โ Strong Answer
-
Use:
- AbortController (preferred)
- or mounted flag
- Cleanup cancels async work
โ Weak Answer
โReact handles itโ ๐ False11. Performance Bottlenecks from Effects
โ Question
How can misuse of lifecycle cause performance issues?๐ Follow-up
- How would you detect this?
โ Strong Answer
- Over-fetching
- unnecessary re-renders
- heavy computations in effects
- profiling tools
- memoization
โ Weak Answer
โEffects are cheapโ12. Dependency Array Design
โ Question
How do you decide what goes into a dependency array?๐ Follow-up
- When is it okay to ignore ESLint warnings?
โ Strong Answer
- Include all values used
- Understand identity vs value
- Rarely suppress warnings (only when safe)
โ Weak Answer
โAdd only what you wantโ13. Lifecycle in Concurrent Rendering
โ Question
How does lifecycle behave differently in concurrent React?๐ Follow-up
- What problems does it solve?
โ Strong Answer
- Effects run only for committed renders
- Prevents inconsistent UI
โ Weak Answer
โNo differenceโ14. Real-world Bug: Duplicate API Calls
โ Question
Your API is called twice on mount. Why?๐ Follow-up
- How would you confirm it?
โ Strong Answer
- Strict Mode double invoke
- OR multiple mounts
- OR dependency issues
โ Weak Answer
โReact bugโ15. Event Listener Lifecycle Design
โ Question
How do you safely manage global event listeners?๐ Follow-up
- What happens if handler changes?
โ Strong Answer
- Add/remove in effect
- Ensure stable handler reference
โ Weak Answer
โAdd onceโ16. Handling Rapid Prop Changes
โ Question
Component receives rapidly changing props triggering effects. How do you handle it?๐ Follow-up
- Debounce vs throttle?
โ Strong Answer
- Debounce input
- Cancel previous work
- Avoid race conditions
โ Weak Answer
โLet it runโ17. Lifecycle vs State Management Libraries
โ Question
When should lifecycle logic move out of components?๐ Follow-up
- Compare React Query / Redux
โ Strong Answer
- Complex async โ move to data layer
- Reduces duplication
โ Weak Answer
โAlways keep in componentโ18. Debugging Memory Leaks
โ Question
How do you identify and fix lifecycle-related memory leaks?๐ Follow-up
- Tools youโd use?
โ Strong Answer
-
Look for:
- missing cleanup
- intervals
- listeners
- Use DevTools profiling
โ Weak Answer
โReact handles cleanupโ19. Designing Lifecycle for Large Systems
โ Question
How do you manage lifecycle complexity in large apps?๐ Follow-up
- What patterns scale well?
โ Strong Answer
- Custom hooks
- separation of concerns
- data layer abstraction
- avoid effect chaining
โ Weak Answer
โUse more useEffectโ๐ Final Insight
A senior-level understanding means:- Lifecycle = synchronization model
- Effects = controlled side effects
-
Focus on:
- correctness
- performance
- predictability
- Think in data flow
- Avoid unnecessary effects
- Handle async + cleanup rigorously