π React Event Handling β Complete Theory Guide
1. π§ Introduction
πΉ What is Event Handling?
Event handling in React refers to the process of capturing and responding to user interactions such as:- Clicks (
onClick) - Input changes (
onChange) - Form submissions (
onSubmit) - Keyboard events (
onKeyDown) - Mouse events (
onMouseEnter, etc.)
πΉ Why is it Important in React?
Event handling is critical because:- React apps are UI-driven β user interactions control behavior
- Enables state updates β re-render β UI changes
- Connects user actions β business logic
-
Essential for:
- Forms
- Navigation
- API calls
- Animations
πΉ When and Why We Use It
We use event handling whenever:- A user interacts with the UI
- We need to update state or trigger logic
-
We want to:
- Validate forms
- Submit data
- Toggle UI elements
- Control components
2. βοΈ Concepts / Internal Workings
πΉ 2.1 Synthetic Events
React uses a wrapper called SyntheticEvent instead of native DOM events.Why?
- Cross-browser compatibility
- Consistent behavior
event.targetevent.preventDefault()event.stopPropagation()
πΉ 2.2 Event Delegation
React does not attach events directly to DOM nodes. Instead:- It attaches a single listener at the root
- Uses event delegation
Benefits:
- Better performance
- Fewer event listeners
- Efficient memory usage
πΉ 2.3 Event Pooling (Important Concept)
Earlier React versions reused event objects (pooling). β οΈ In modern React (17+):- Event pooling is removed
- You can safely use events asynchronously
πΉ 2.4 Binding this (Class Components)
In class components, event handlers lose context.
- Bind in constructor
- Use arrow functions
πΉ 2.5 Relationship with State
Event handling is tightly coupled with state updates:πΉ 2.6 Relationship with Re-rendering
- Every event handler can trigger a re-render
- React batches updates for performance
πΉ 2.7 Prevent Default Behavior
- Forms
- Links
- Native browser actions
3. π» Syntax & Examples
πΉ 3.1 Basic Click Event
πΉ 3.2 Inline Event Handler
πΉ 3.3 Passing Arguments
πΉ 3.4 Event Object Usage
πΉ 3.5 Input Handling
πΉ 3.6 Form Submission
πΉ 3.7 Keyboard Events
πΉ 3.8 Conditional Handling
πΉ 3.9 Class Component Example
4. β οΈ Edge Cases / Common Mistakes
β 4.1 Calling Function Instead of Passing
β 4.2 Forgetting preventDefault
β 4.3 Losing this in Class Components
β 4.4 Overusing Inline Functions
- New function every render
- Can hurt performance in large lists
β 4.5 Stale State in Handlers
- Uses outdated value
β 4.6 Event Propagation Issues
β 4.7 Async Issues (Old React Knowledge)
Old:5. β Best Practices
πΉ 5.1 Keep Handlers Clean & Small
Bad:πΉ 5.2 Avoid Inline Functions in Large Lists
Use:πΉ 5.3 Use Functional Updates for State
πΉ 5.4 Use useCallback for Optimization
- Passing handlers to child components
- Avoiding unnecessary re-renders
πΉ 5.5 Separate Logic from UI
πΉ 5.6 Prevent Unnecessary Re-renders
- Memoize handlers when needed
- Avoid recreating functions unnecessarily
πΉ 5.7 Use Semantic Events Properly
onChangefor inputsonSubmitfor formsonClickfor buttons
πΉ 5.8 Handle Errors Gracefully
π§© Summary
Event handling in React is:-
Declarative (
onClick={...}) - Efficient (via event delegation)
- Cross-browser (via SyntheticEvents)
-
Deeply integrated with:
- State
- Rendering
- Component lifecycle
Below is a senior-level, in-depth interview set on React Event Handling. These are designed to probe how you think, not just what you know.
π§ React Event Handling β Advanced Conceptual Questions
1. How does Reactβs event system differ from the native DOM event system?
β Strong Answer
React uses a Synthetic Event system, which is a wrapper around native DOM events.Key Differences:
-
Delegation:
- React attaches a single event listener at the root
- Native DOM attaches listeners directly to elements
-
Cross-browser normalization:
- Synthetic events ensure consistent behavior across browsers
-
Controlled lifecycle:
- React manages event flow in sync with its rendering model
Example:
- React maps
onClickβ root listener β dispatches internally
π€ Why this design?
- Performance (fewer listeners)
- Predictability across browsers
- Integration with Reactβs reconciliation
β οΈ Common Weak Answer
βReact events are same as DOM events but easier.ββ Lacks understanding of delegation and abstraction layer.
2. Why did React remove event pooling in React 17?
β Strong Answer
Earlier, React reused event objects (pooling) to reduce memory allocations.Problem:
- Async usage broke:
Solution:
- React 17 removed pooling β events persist naturally
π€ Trade-off
- Slight increase in memory usage
- Much better developer experience and fewer bugs
β οΈ Weak Answer
βBecause it caused bugs.ββ Doesnβt explain what bugs or trade-offs.
3. Explain how event delegation improves performance in React.
β Strong Answer
Instead of attaching event listeners to each DOM node:- React attaches one listener per event type at root
- Uses bubbling to detect target
Benefits:
- Reduced memory footprint
- Faster mounting/unmounting
- Better scalability in large lists
π€ Real-world scenario
Rendering 10,000 items:- Native: 10,000 listeners
- React: 1 listener
β οΈ Trade-off
- Slight complexity in event dispatching logic
4. How does React handle event propagation differently from the DOM?
β Strong Answer
React mimics DOM propagation but controls it internally.Phases:
- Capturing
- Bubbling (default in React)
Example:
Key Insight:
- React propagation happens within its virtual event system
- Still maps to native propagation under the hood
β οΈ Edge Case
Mixing React + native listeners can break expectations.5. What happens if you mix native DOM events with React events?
β Strong Answer
This creates two parallel event systems:- React synthetic system
- Native DOM system
Problem:
stopPropagation()in React may NOT stop native listeners
Example:
π€ Recommendation
- Avoid mixing unless necessary
- If needed β understand execution order
6. Why are inline event handlers considered problematic in certain scenarios?
β Strong Answer
Issues:
- New function created on every render
- Breaks referential equality
- Causes unnecessary re-renders in child components
Example Problem:
React.memo, child re-renders
Better:
β οΈ Trade-off
- Premature optimization vs readability
7. How do event handlers interact with Reactβs batching system?
β Strong Answer
React batches state updates inside event handlers.Why?
- Improves performance
- Avoids unnecessary intermediate renders
Advanced Insight:
- In React 18 β batching works even in async contexts
8. What is the risk of stale closures in event handlers?
β Strong Answer
Event handlers can capture outdated state values.Fix:
Real-world issue:
- Rapid clicks
- Async events
- Debounced handlers
9. How does React ensure consistency between UI and event handling?
β Strong Answer
React uses:- Virtual DOM
- Controlled updates
- Synthetic events tied to render cycle
Insight:
- Events trigger state updates
- State drives UI β ensures consistency
Why important?
Prevents:- UI desync bugs
- Race conditions
10. When should you use useCallback for event handlers?
β Strong Answer
Use when:- Passing handler to child components
- Child uses
React.memo - Preventing unnecessary re-renders
Example:
Trade-off:
- Overuse increases complexity
- Not always needed
11. Explain controlled vs uncontrolled inputs in event handling.
β Strong Answer
Controlled:
- React controls state
Uncontrolled:
- DOM controls state
Trade-offs:
12. Why is preventDefault() critical in form handling?
β Strong Answer
Prevents browserβs default behavior (page reload).Without it:
- SPA breaks
- Page refresh occurs
13. How do you handle expensive logic inside event handlers?
β Strong Answer
Strategies:- Debouncing
- Throttling
- Moving logic outside render
- Using
useCallback
Example:
14. What are the implications of event handling in large lists?
β Strong Answer
Challenges:- Performance
- Re-renders
- Memory usage
Solutions:
- Event delegation (React already does this)
- Memoization
- Avoid inline handlers
15. How does React handle events in concurrent rendering?
β Strong Answer
React prioritizes updates:- User interactions = high priority
- Background updates = low priority
Insight:
- Ensures responsive UI
- Event handlers remain synchronous triggers
16. Why should event handlers be pure (or close to pure)?
β Strong Answer
Avoid:- Side effects during render
- Unpredictable behavior
Good:
Bad:
17. How do you debug event-related bugs in React?
β Strong Answer
Approach:- Log event object
- Check propagation
- Verify handler binding
- Inspect state updates
Tools:
- React DevTools
- Console tracing
18. What are common pitfalls with event propagation in nested components?
β Strong Answer
Issues:- Unexpected bubbling
- Multiple handlers firing
Fix:
Real-world example:
- Modal inside overlay
- Dropdown inside menu
π― Final Takeaway
A senior engineer understands that event handling in React is:-
Not just syntax (
onClick) -
But a system involving:
- Delegation
- Synthetic abstraction
- State lifecycle
- Performance trade-offs
Below is a senior-level MCQ set (18 questions) on React Event Handling, designed to test deep understanding, internal behavior, and real-world pitfalls.
π§ React Event Handling β Advanced MCQs
1. What will be logged?
Options:
A. 0 B. 1 C. 2 D. Undefinedβ Correct Answer: A
π‘ Explanation:
countinside handler is stale (closure) β still0- React batches updates β both updates use same
count
β Why others are wrong:
- B/C: assume synchronous updates (incorrect in React)
- D:
countis defined
2. Which behavior occurs when mixing native and React events?
Options:
A. Only βReactβ logs B. Only βNativeβ logs C. Both may log D. None logsβ Correct Answer: C
π‘ Explanation:
- React uses synthetic system
- Native listeners are separate
stopPropagation()may not stop native handler
β Why others are wrong:
- A: ignores native system
- B: React handler will fire
- D: incorrect
3. What is the main reason React uses event delegation?
Options:
A. To simplify syntax B. To reduce memory usage C. To avoid re-renders D. To eliminate bubblingβ Correct Answer: B
π‘ Explanation:
- One listener at root instead of many
- Improves scalability
β Why others are wrong:
- A: syntax unrelated
- C: delegation doesnβt affect re-renders directly
- D: bubbling still exists
4. What happens here?
Options:
A. Runs on click B. Runs on render C. Throws error always D. Runs twiceβ Correct Answer: B
π‘ Explanation:
- Function is invoked immediately during render
β Why others are wrong:
- A: incorrect timing
- C: not necessarily an error
- D: not guaranteed
5. Which is the best fix for stale state updates?
Options:
A.setCount(count + 1)
B. setCount(prev => prev + 1)
C. setTimeout(() => setCount(count + 1))
D. count++
β Correct Answer: B
π‘ Explanation:
- Functional updates ensure latest state
β Why others are wrong:
- A: stale closure risk
- C: still stale
- D: mutates state (wrong)
6. Why can inline handlers cause performance issues?
Options:
A. They block rendering B. They create new function references C. They prevent batching D. They disable delegationβ Correct Answer: B
π‘ Explanation:
- New function every render β breaks memoization
β Why others are wrong:
- A: no blocking
- C: batching unaffected
- D: delegation unaffected
7. What does React 17 change about events?
Options:
A. Removes event delegation B. Removes event pooling C. Disables bubbling D. Makes events asyncβ Correct Answer: B
π‘ Explanation:
- Events no longer reused β safer async usage
β Why others are wrong:
- A: delegation still exists
- C: bubbling still exists
- D: events are still sync triggers
8. What happens in this scenario?
Options:
A. Only Parent logs B. Only Child logs C. Child then Parent logs D. Parent then Child logsβ Correct Answer: C
π‘ Explanation:
- Event bubbles upward
β Why others are wrong:
- A/B: ignore propagation
- D: wrong order
9. When should useCallback be used for handlers?
Options:
A. Always B. Never C. When passing to memoized children D. Only for API callsβ Correct Answer: C
π‘ Explanation:
- Prevents unnecessary re-renders
β Why others are wrong:
- A: overkill
- B: ignores optimization
- D: unrelated
10. What does preventDefault() do?
Options:
A. Stops bubbling B. Stops default browser behavior C. Stops React rendering D. Stops event creationβ Correct Answer: B
β Why others are wrong:
- A: thatβs
stopPropagation - C/D: incorrect
11. Why might this fail?
Options:
A. Because of async React rendering B. Because of event pooling (old React) C. Because of delegation D. Because of batchingβ Correct Answer: B
π‘ Explanation:
- Old React reused events β nullified later
12. What is true about React event propagation?
Options:
A. React disables bubbling B. React only supports capturing C. React mimics DOM propagation D. React events donβt propagateβ Correct Answer: C
13. Which scenario causes unnecessary re-renders?
Options:
A. Stable handler reference B. Inline handler in list items C. UsinguseCallback
D. Event delegation
β Correct Answer: B
14. What is the effect of this code?
Options:
A. Stops default behavior B. Stops bubbling C. Stops capturing D. Stops renderingβ Correct Answer: B
15. Why is directly manipulating DOM inside handlers discouraged?
Options:
A. It crashes React B. It breaks Reactβs declarative model C. It disables events D. It stops re-renderβ Correct Answer: B
π‘ Explanation:
- React expects UI to be derived from state
16. What happens with multiple state updates in one handler?
Options:
A. Multiple renders B. Single batched render C. No render D. Random behaviorβ Correct Answer: B
17. What is the main benefit of Synthetic Events?
Options:
A. Faster rendering B. Cross-browser consistency C. Smaller bundle size D. No propagationβ Correct Answer: B
18. Which is the safest way to pass arguments to handlers?
Options:
A.onClick={handleClick(arg)}
B. onClick={() => handleClick(arg)}
C. onClick={handleClick.bind(arg)}
D. onClick={arg}
β Correct Answer: B
π‘ Explanation:
- Ensures function runs only on click
β Why others are wrong:
- A: executes immediately
- C: incorrect binding usage
- D: invalid
π― Final Insight
These questions test whether you understand:- Internal event system (Synthetic + delegation)
- Rendering & state interactions
- Performance implications
- Real-world debugging scenarios
Below is a senior-level set of 18 React Event Handling coding problems designed to simulate real-world engineering scenarios. Each problem focuses on decision-making, edge cases, and internal behavior, not boilerplate.
π§ React Event Handling β Coding Problems (Senior Level)
1. Debounced Search Input (Medium)
π§© Problem
Build a search input that:- Calls an API only after user stops typing for 500ms
- Cancels previous pending calls
βοΈ Constraints
- No unnecessary API calls
- Must handle rapid typing
β Expected Behavior
Typing:r β re β rea
β Only one API call for βreaβ
β οΈ Edge Cases
- Fast typing
- Component unmount during debounce
π‘ Solution
UsesetTimeout + cleanup OR debounce utility.
π§ Key Insight
Event (onChange) triggers state β debounced effect handles logic.
2. Prevent Double Submission (Medium)
π§© Problem
Prevent a form from being submitted multiple times on rapid clicks.βοΈ Constraints
- Disable button during submission
- Re-enable on response
β Expected Behavior
Clicking multiple times β only one API callπ‘ Solution
π§ Insight
Event handler must guard against re-entrancy3. Click Outside to Close Modal (Medium)
π§© Problem
Close modal when user clicks outside it.βοΈ Constraints
- Must not close when clicking inside
π‘ Solution
β οΈ Edge Cases
- Event propagation issues
- Modal inside portals
4. Stop Event Propagation in Nested Menus (Medium)
π§© Problem
Dropdown inside a clickable parent β prevent parent click.π‘ Solution
π§ Insight
Understand bubbling vs control5. Throttled Scroll Handler (Hard)
π§© Problem
Track scroll position without performance issues.βοΈ Constraints
- Fire at most once every 200ms
π‘ Solution
β οΈ Edge Cases
- Cleanup on unmount
- Passive listeners
6. Keyboard Navigation System (Hard)
π§© Problem
Navigate a list using arrow keys.π‘ Solution
β οΈ Edge Cases
- Bounds handling
- Accessibility
7. Drag-to-Select Grid (Hard)
π§© Problem
Click + drag to select items in a grid.π‘ Solution
Use:onMouseDownonMouseEnteronMouseUp
π§ Insight
Combine multiple event types into one interaction8. Prevent Stale State in Rapid Clicks (Medium)
π§© Problem
Fix counter increment bug on rapid clicks.π‘ Solution
π§ Insight
Closure vs latest state9. Input with Validation on Blur (Medium)
π§© Problem
Validate only when user leaves input.π‘ Solution
β οΈ Edge Cases
- User never blurs
- Accessibility concerns
10. Global Shortcut Handler (Hard)
π§© Problem
PressCtrl + K to open search.
π‘ Solution
β οΈ Edge Cases
- Focused inputs
- OS differences
11. Infinite Scroll Loader (Hard)
π§© Problem
Load more items when reaching bottom.π‘ Solution
Use scroll event + threshold check.π§ Insight
Avoid excessive calls β throttle/debounce12. Controlled vs Uncontrolled Form Switch (Hard)
π§© Problem
Switch between controlled and uncontrolled input dynamically.β οΈ Edge Case
React warns about switching modesπ‘ Solution
Always keep consistent control13. Event Handler Memory Leak (Hard)
π§© Problem
Fix memory leak caused by event listeners.π‘ Solution
14. Optimized List Item Click Handlers (Hard)
π§© Problem
Large list β avoid re-rendering all items.π‘ Solution
- Use
useCallback - Pass stable handlers
15. Double Click vs Single Click Conflict (Hard)
π§© Problem
Handle both click and double click differently.π‘ Solution
Use timer to differentiate.β οΈ Edge Case
Timing conflicts16. Form Autosave on Input Change (Hard)
π§© Problem
Auto-save after user stops typing.π‘ Solution
Debounce insideonChange
17. Prevent Scroll Jump on Re-render (Hard)
π§© Problem
List re-renders β scroll resetsπ‘ Solution
Store scroll position before update18. Nested Drag + Click Conflict (Hard)
π§© Problem
Dragging triggers click unintentionallyπ‘ Solution
Track drag stateπ― Final Takeaways
These problems test:- Event lifecycle understanding
- State + event coordination
- Performance optimization
- Real-world UX handling
- Edge-case awareness
Below is a senior-level set of 18 debugging challenges focused on React Event Handling. These simulate real production bugsβsubtle, non-obvious, and rooted in how React actually works.
π§ React Event Handling β Debugging Challenges
1. Stale State in Rapid Clicks
π Buggy Code
β Whatβs Wrong
Count increases by 1 instead of 2π€ Why It Happens
- Both updates use same stale closure value
- React batches updates
β Fix
π§ Best Practice
Always use functional updates when next state depends on previous.2. Immediate Function Execution
π Buggy Code
β Whatβs Wrong
Function executes during render, not on clickπ€ Why
JS evaluates function immediatelyβ Fix
π§ Best Practice
Pass reference, not invocation3. Event Listener Memory Leak
π Buggy Code
β Whatβs Wrong
Listener never removed β memory leakπ€ Why
Component unmount doesnβt clean upβ Fix
π§ Best Practice
Always clean up side effects4. Click Outside Not Working Properly
π Buggy Code
β Whatβs Wrong
Fails when clicking child elementsπ€ Why
target β container
β Fix
π§ Best Practice
Usecontains() for DOM hierarchy checks
5. stopPropagation Not Working
π Buggy Code
β Whatβs Wrong
Parent still triggersπ€ Why
React and native events are separate systemsβ Fix
Avoid mixing systems OR handle at same layerπ§ Best Practice
Stick to React event system unless necessary6. Inline Handler Causing Re-renders
π Buggy Code
β Whatβs Wrong
Child re-renders unnecessarilyπ€ Why
New function every renderβ Fix
π§ Best Practice
Stabilize handler references when needed7. Debounce Not Working Correctly
π Buggy Code
β Whatβs Wrong
Event becomes invalidπ€ Why
Synthetic event reused (older React)β Fix
π§ Best Practice
Extract values before async usage8. Form Reloading Page
π Buggy Code
β Whatβs Wrong
Page refresh occursπ€ Why
Default browser behaviorβ Fix
π§ Best Practice
Always handle form defaults in SPA9. Drag Triggering Click
π Buggy Code
β Whatβs Wrong
Click fires after dragπ€ Why
Mouseup triggers clickβ Fix
π§ Best Practice
Track interaction state explicitly10. Multiple API Calls on Input
π Buggy Code
β Whatβs Wrong
API spamπ€ Why
Fires on every keystrokeβ Fix
Debounce inputπ§ Best Practice
Throttle or debounce expensive handlers11. Incorrect useEffect Dependency
π Buggy Code
β Whatβs Wrong
Listener added repeatedlyπ€ Why
handleClick changes every render
β Fix
π§ Best Practice
Stabilize dependencies12. Keyboard Event Not Triggering
π Buggy Code
β Whatβs Wrong
Event not firingπ€ Why
Div not focusableβ Fix
π§ Best Practice
Ensure element is focusable13. PreventDefault Misuse
π Buggy Code
β Whatβs Wrong
Unnecessary callπ€ Why
No default behavior for buttonβ Fix
Remove itπ§ Best Practice
Use only when needed14. Event Handler Blocking UI
π Buggy Code
β Whatβs Wrong
UI freezesπ€ Why
Main thread blockedβ Fix
Move heavy logic to async/taskπ§ Best Practice
Keep handlers lightweight15. Incorrect Ref Usage in Events
π Buggy Code
β Whatβs Wrong
Always falseπ€ Why
Ref object β DOM nodeβ Fix
π§ Best Practice
Use.current
16. Double Click Conflict
π Buggy Code
β Whatβs Wrong
Single click fires before doubleπ€ Why
Browser behaviorβ Fix
Use delay logic17. Scroll Listener Performance Issue
π Buggy Code
β Whatβs Wrong
Too many executionsπ€ Why
Scroll fires frequentlyβ Fix
Throttle handlerπ§ Best Practice
Always optimize high-frequency events18. Missing Cleanup in Custom Hook
π Buggy Code
β Whatβs Wrong
Leak across multiple mountsπ€ Why
No cleanupβ Fix
Add cleanup functionπ§ Best Practice
Hooks must clean side effectsπ― Final Insight
These bugs reflect real production issues involving:- State + event timing
- Synthetic vs native behavior
- Performance traps
- Subtle lifecycle issues
Below is a senior-level set of 18 production-grade machine coding problems focused on React Event Handling. These mirror real-world systems and top tech interview expectations.
π§ React Event Handling β Machine Coding Problems (Architect Level)
1. Typeahead Search with Cancellation & Ranking
π§© Requirements
- Input field with live suggestions
- Debounced API calls (300β500ms)
- Cancel previous requests on new input
- Highlight matching substrings
π― UI Behavior
- Typing updates suggestions dynamically
- Loading indicator per query
- Keyboard navigation (β β Enter)
π State / Data Flow
query,results,loading,activeIndex- Event β state β async fetch β render
β οΈ Edge Cases
- Rapid typing
- Empty input
- API race conditions
β‘ Performance
- Debounce input
- AbortController for cancellation
ποΈ Architecture
SearchInputSuggestionsList- Custom hook:
useDebouncedSearch
π§ Approach
- Capture
onChange - Debounce query
- Cancel previous request
- Update results safely
2. Multi-Level Dropdown with Keyboard & Click Handling
π§© Requirements
- Nested dropdown menus
- Open/close on hover + click
- Keyboard navigation support
π― UI Behavior
- Arrow keys navigate levels
- Escape closes all
π State
- Active menu path
- Focus index
β οΈ Edge Cases
- Hover vs click conflicts
- Focus loss
β‘ Performance
- Avoid re-renders of all items
ποΈ Architecture
- Recursive menu components
- Context for shared state
π§ Approach
- Combine
onMouseEnter,onClick,onKeyDown - Manage focus explicitly
3. Click Outside + Escape Modal System
π§© Requirements
-
Modal closes on:
- Outside click
- Escape key
π― UI Behavior
- Focus trapped inside modal
- Background scroll disabled
π State
isOpen
β οΈ Edge Cases
- Nested modals
- Portals
β‘ Performance
- Attach listeners only when open
ποΈ Architecture
- Portal-based modal
- Hook:
useOutsideClick
π§ Approach
- Global listeners + ref containment check
4. Infinite Scroll Feed with Smart Prefetch
π§© Requirements
- Load more data when near bottom
- Prefetch next page early
π― UI Behavior
- Seamless loading
- Loader indicator
π State
items,page,loading
β οΈ Edge Cases
- Duplicate calls
- Scroll jump
β‘ Performance
- Throttle scroll handler
- IntersectionObserver preferred
ποΈ Architecture
- Feed component + observer hook
π§ Approach
- Detect threshold β fetch β append
5. Drag-and-Drop Kanban Board
π§© Requirements
- Drag tasks across columns
- Persist order
π― UI Behavior
- Smooth drag feedback
- Drop indicators
π State
- Board structure
β οΈ Edge Cases
- Drag cancel
- Fast movements
β‘ Performance
- Avoid full board re-render
ποΈ Architecture
- Controlled drag state
- Context for board
π§ Approach
- Combine mouse + state tracking
6. Rich Text Editor Toolbar Events
π§© Requirements
- Bold, italic, link insertion
- Selection-based formatting
π― UI Behavior
- Toolbar reacts to selection
π State
- Selection range
β οΈ Edge Cases
- Selection lost on click
β‘ Performance
- Avoid excessive DOM reads
ποΈ Architecture
- Editor + toolbar sync via context
π§ Approach
- Capture selection before event fires
7. Spreadsheet-like Cell Editing System
π§© Requirements
- Click to edit cell
- Arrow key navigation
π― UI Behavior
- Enter/Tab moves focus
π State
- Active cell
β οΈ Edge Cases
- Blur vs key conflicts
β‘ Performance
- Virtualize rows
ποΈ Architecture
- Grid + cell components
π§ Approach
- Event-driven navigation system
8. Global Shortcut Manager
π§© Requirements
- Register shortcuts like
Ctrl+S,Ctrl+K
π― UI Behavior
- Works app-wide
π State
- Registered handlers
β οΈ Edge Cases
- Input focus conflicts
β‘ Performance
- Single global listener
ποΈ Architecture
- Context-based registry
π§ Approach
- Normalize key events
9. Image Zoom + Pan Viewer
π§© Requirements
- Scroll to zoom
- Drag to pan
π― UI Behavior
- Smooth zoom/pan
β οΈ Edge Cases
- Boundary overflow
β‘ Performance
- Throttle wheel events
ποΈ Architecture
- Transform-based rendering
π§ Approach
- Combine wheel + mouse events
10. Auto-Save Form with Conflict Resolution
π§© Requirements
- Save after inactivity
- Detect conflicts
π― UI Behavior
- Save indicator
β οΈ Edge Cases
- Rapid edits
- API delay
β‘ Performance
- Debounce input
ποΈ Architecture
- Hook for autosave
π§ Approach
- Track dirty state + debounce
11. Virtualized List with Selection & Multi-Select
π§© Requirements
- Large list (10k+ items)
- Shift + click selection
π― UI Behavior
- Smooth scrolling
β οΈ Edge Cases
- Selection persistence
β‘ Performance
- Virtualization mandatory
ποΈ Architecture
- Windowing library + state manager
π§ Approach
- Track selection range
12. Resizable Panels (Split View)
π§© Requirements
- Drag divider to resize panels
π― UI Behavior
- Smooth resizing
β οΈ Edge Cases
- Min/max width
β‘ Performance
- Use requestAnimationFrame
ποΈ Architecture
- Layout container + drag handler
π§ Approach
- Track mouse movement globally
13. Gesture-Based Mobile Carousel
π§© Requirements
- Swipe left/right
- Momentum scrolling
β οΈ Edge Cases
- Touch cancel
β‘ Performance
- Passive listeners
ποΈ Architecture
- Touch event abstraction
π§ Approach
- Track touch delta + velocity
14. Collaborative Cursor Tracker (Realtime)
π§© Requirements
- Show multiple usersβ cursors
π― UI Behavior
- Smooth cursor movement
β οΈ Edge Cases
- Network lag
β‘ Performance
- Throttle mouse move events
ποΈ Architecture
- WebSocket + event throttling
π§ Approach
- Emit + render positions efficiently
15. Nested Drag-and-Drop Tree
π§© Requirements
- Drag items within tree structure
β οΈ Edge Cases
- Invalid drops
β‘ Performance
- Avoid re-rendering entire tree
ποΈ Architecture
- Recursive components
π§ Approach
- Track drag path + drop target
16. Inline Editable Table with Validation
π§© Requirements
- Click to edit
- Validate on blur
β οΈ Edge Cases
- Invalid input
β‘ Performance
- Isolate cell updates
ποΈ Architecture
- Controlled inputs per cell
π§ Approach
- Separate edit vs display state
17. Notification System with Auto Dismiss + Pause on Hover
π§© Requirements
- Auto-dismiss after 5s
- Pause on hover
β οΈ Edge Cases
- Multiple notifications
β‘ Performance
- Efficient timers
ποΈ Architecture
- Notification manager
π§ Approach
- Combine timers + hover events
18. Zoomable Timeline with Scroll Sync
π§© Requirements
- Scroll horizontally
- Zoom timeline
β οΈ Edge Cases
- Sync multiple tracks
β‘ Performance
- Throttle scroll + transform
ποΈ Architecture
- Shared scroll state
π§ Approach
- Event coordination system
π― Final Insight
These problems test:- Event orchestration (multiple event types)
- State synchronization
- Performance under heavy interaction
- Real-world UX constraints
- Architectural thinking
Below is a FAANG-level interview set (18 questions) on React Event Handling, designed to evaluate deep understanding, system thinking, and real-world decision-making.
π§ React Event Handling β Senior Interview Questions
1. How would you design an event-heavy component (e.g., canvas editor or drag system) to avoid performance bottlenecks?
π Follow-ups
- How do you handle high-frequency events like
mousemove? - Where would you store transient vs persistent state?
β Strong Answer
- Use throttling / requestAnimationFrame
- Keep transient state outside React (refs) to avoid re-renders
- Use event delegation/global listeners
- Batch updates and minimize DOM writes
β Weak Answer
βUse useState and optimize laterββ Ignores render cost and event frequency impact
2. Explain how Reactβs event delegation impacts debugging complex UI interactions.
π Follow-ups
- How would you debug propagation issues?
- What happens with portals?
β Strong Answer
- Events handled at root β not attached per node
- Debugging requires understanding synthetic propagation
- Portals still participate in React tree propagation
β Weak Answer
βEvents work like DOM eventsββ Misses abstraction layer
3. You notice unnecessary re-renders in a list with click handlers. How do you diagnose and fix it?
π Follow-ups
- How do you confirm handler identity changes?
- When is
useCallbackjustified?
β Strong Answer
- Check referential equality of handlers
- Inline functions cause re-renders
- Use
useCallbackselectively
β Weak Answer
βWrap everything in useCallbackββ Over-optimization without reasoning
4. How would you design a global keyboard shortcut system in a large app?
π Follow-ups
- How do you avoid conflicts?
- How do you scope shortcuts?
β Strong Answer
- Single global listener
- Context-based registration system
- Ignore events from inputs
- Normalize keys
β Weak Answer
βAdd event listener in each componentββ Leads to duplication and conflicts
5. Why can mixing native DOM events with React events cause bugs?
π Follow-ups
- How does
stopPropagationbehave?
β Strong Answer
- Two event systems run independently
- Reactβs stopPropagation may not affect native listeners
β Weak Answer
βBecause React is differentββ Lacks mechanism understanding
6. How do you handle stale state inside event handlers?
π Follow-ups
- When does this become critical?
β Strong Answer
- Use functional updates
- Understand closure capture
β Weak Answer
βJust use latest stateββ Doesnβt explain how
7. Design a robust βclick outsideβ detection system.
π Follow-ups
- How do you handle portals?
- What about nested components?
β Strong Answer
- Use
ref.contains(e.target) - Attach listener at document level
- Handle portal edge cases
β Weak Answer
βCompare element directlyββ Fails for nested DOM
8. How would you optimize scroll or resize handlers in React?
π Follow-ups
- When to use passive listeners?
β Strong Answer
- Throttle/debounce
- Use passive listeners
- Avoid state updates per event
β Weak Answer
βUse useEffectββ Doesnβt address performance
9. What are the trade-offs of using inline event handlers?
π Follow-ups
- When are they acceptable?
β Strong Answer
- Simplicity vs referential instability
- Acceptable in small components
β Weak Answer
βThey are badββ Oversimplified
10. How do you prevent multiple rapid submissions in a form?
π Follow-ups
- How do you handle race conditions?
β Strong Answer
- Disable button
- Track loading state
- Prevent duplicate requests
β Weak Answer
βUse debounceββ Not sufficient for submissions
11. How does React batching affect event-driven state updates?
π Follow-ups
- What changed in React 18?
β Strong Answer
- Multiple updates β single render
- React 18 extends batching to async
β Weak Answer
βIt improves performanceββ Lacks mechanism detail
12. How would you debug an issue where an event handler fires twice?
π Follow-ups
- Could Strict Mode affect this?
β Strong Answer
- Check Strict Mode double-invocation
- Verify event listener duplication
β Weak Answer
βBug in Reactββ No debugging approach
13. How do you manage event handling in large lists (10k items)?
π Follow-ups
- How does React help?
β Strong Answer
- Use event delegation
- Avoid inline handlers
- Virtualization
β Weak Answer
βReact handles itββ Ignores scaling issues
14. How would you handle drag-and-drop interactions without performance issues?
π Follow-ups
- How do you avoid re-renders?
β Strong Answer
- Use refs for transient state
- Throttle updates
- Avoid state on every move
β Weak Answer
βUpdate state on every mouse moveββ Causes jank
15. What are common pitfalls with event propagation in nested components?
π Follow-ups
- Real-world example?
β Strong Answer
- Unexpected bubbling
- Fix with stopPropagation carefully
β Weak Answer
βUse stopPropagation everywhereββ Leads to fragile code
16. How would you design an autosave feature triggered by user input?
π Follow-ups
- How do you avoid API spam?
β Strong Answer
- Debounce input
- Track dirty state
- Cancel previous requests
β Weak Answer
βCall API on every changeββ Inefficient
17. Why should event handlers avoid heavy synchronous work?
π Follow-ups
- What happens to the UI thread?
β Strong Answer
- Blocks main thread
- Causes UI freeze
- Move work to async/task queue
β Weak Answer
βBecause itβs slowββ No technical reasoning
18. How do you ensure accessibility in event-driven components?
π Follow-ups
- Keyboard support?
β Strong Answer
- Use semantic elements
- Support keyboard events
- Manage focus
β Weak Answer
βUse ARIAββ Too vague
π― Final Evaluation Criteria
A strong candidate demonstrates:- Deep understanding of event system internals
- Ability to reason about performance & scaling
- Awareness of real-world edge cases
- Strong debugging mindset
- Thoughtful trade-off decisions