React Advanced Topics 3 — Questions and Answers
Question 1: What is the React Context API primarily used for?
- Sharing data across the component tree without prop drilling (Correct answer)
- Making HTTP requests
- Animating components
- Managing CSS modules
Correct answer: Sharing data across the component tree without prop drilling
Context lets you pass data through the tree without manually passing props at every level.
Question 2: What does a custom hook allow you to do?
- Extract and reuse stateful logic across components (Correct answer)
- Override React's internal scheduler
- Render outside the root DOM node
- Bypass the virtual DOM
Correct answer: Extract and reuse stateful logic across components
Custom hooks package reusable stateful logic into a function whose name starts with 'use'.
Question 3: What is the purpose of React.lazy?
- To delay state updates
- To enable code-splitting by dynamically importing a component (Correct answer)
- To memoize props
- To lazily initialize context
Correct answer: To enable code-splitting by dynamically importing a component
React.lazy lets you render a dynamically imported component for code-splitting.
Question 4: Which component must wrap a React.lazy component to handle its loading state?
- Fragment
- Suspense (Correct answer)
- StrictMode
- Profiler
Correct answer: Suspense
Suspense displays fallback UI while a lazy component is loading.
Question 5: What does the useReducer hook help manage?
- Complex state logic with multiple sub-values or transitions (Correct answer)
- DOM refs only
- CSS animations
- Network caching
Correct answer: Complex state logic with multiple sub-values or transitions
useReducer is suited to complex state managed through dispatched actions and a reducer function.
Question 6: What is a portal in React (ReactDOM.createPortal)?
- A way to render children into a DOM node outside the parent hierarchy (Correct answer)
- A way to share state globally
- A type of error boundary
- A server-side rendering technique
Correct answer: A way to render children into a DOM node outside the parent hierarchy
Portals render children into a different DOM node while keeping them in the React tree.
Question 7: How do events behave inside a React portal?
- They do not propagate at all
- They bubble through the React tree, not the DOM tree (Correct answer)
- They only fire on the portal's DOM parent
- They are blocked by Suspense
Correct answer: They bubble through the React tree, not the DOM tree
Even though a portal renders elsewhere in the DOM, events bubble up the React component tree.
What is the React Context API primarily used for?