Episode 2 — React Frontend Architecture NextJS / 2.4 — React Lifecycle Methods
2.4 — Exercise Questions: React Lifecycle Methods
Practice makes permanent. Work through these in order — each builds on the previous.
How to use this material
- Try answering before checking hints
- Code the hands-on questions in a real project
- Revisit questions you got wrong after 24 hours
- Discuss tricky ones with peers
- Build something small that combines 3+ concepts
2.4.a — Class Components Lifecycle (Q1–Q15)
Q1. What are the minimum requirements for a valid React class component? Write the smallest possible class component that renders "Hello".
Q2. Why must you call super(props) before using this in a constructor? What error do you get if you don't?
Q3. What is the difference between super() and super(props) in a class component constructor? When would this.props be undefined?
Q4. Write a class component that initialises state with count: 0 using (a) the constructor and (b) class field syntax. Which is shorter?
Q5. Explain why this code crashes: <button onClick={this.handleClick}>. Write three different fixes.
Q6. What's the difference between a prototype method and an arrow class field in terms of memory? When does the difference matter?
Q7. Predict the output: You call this.setState({ count: this.state.count + 1 }) three times in a row inside a click handler. What is the final value of count if it started at 0? Why?
Q8. Rewrite Q7 using the updater function form of setState. What's the final value now?
Q9. Does setState immediately update this.state? Write code that proves your answer using console.log before and after setState.
Q10. How does setState shallow merge work? If state is { a: 1, b: 2, c: 3 } and you call this.setState({ b: 99 }), what is the resulting state?
Q11. Write code demonstrating the deep merge problem: state has a nested user.address.city field. Show the wrong way and right way to update just the city.
Q12. What can render() return? List at least 6 valid return types.
Q13. Why can't you call setState inside render()? What would happen?
Q14. Convert this class component to a function component:
class Greeting extends Component {
state = { name: '' };
handleChange = (e) => { this.setState({ name: e.target.value }); };
render() {
return <input value={this.state.name} onChange={this.handleChange} />;
}
}
Q15. Name one React feature that still requires a class component in 2024+. Why hasn't a hook equivalent been created?
2.4.b — React's Lifecycle Methods (Q16–Q30)
Q16. Draw (or describe) the complete mounting sequence: which lifecycle methods fire, in what order?
Q17. What is componentDidMount used for? Give three common use cases.
Q18. Can you call setState in componentDidMount? What happens — how many renders does the user see?
Q19. What triggers the updating phase? Name all three triggers.
Q20. Write a componentDidUpdate that fetches new data when a userId prop changes. Include the guard condition.
Q21. What happens if you call setState inside componentDidUpdate without a guard condition?
Q22. What is shouldComponentUpdate? Write one that only re-renders when props.count changes.
Q23. What does forceUpdate() do? Does it respect shouldComponentUpdate?
Q24. Explain getSnapshotBeforeUpdate. When does it run relative to the DOM update? What is its return value used for?
Q25. Write a componentWillUnmount that cleans up: (a) an interval, (b) an event listener, and (c) an AbortController.
Q26. What's the difference between getDerivedStateFromError and componentDidCatch? Which shows fallback UI and which logs errors?
Q27. Error boundaries catch errors in render, lifecycle methods, and constructors. Name three types of errors they do NOT catch.
Q28. Write a minimal error boundary component that shows "Something went wrong" and has a "Try again" button.
Q29. What is PureComponent? How does it differ from Component? What kind of comparison does it perform?
Q30. Give an example where PureComponent fails to prevent re-renders (hint: new object reference every render).
2.4.c — useEffect Hook (Q31–Q45)
Q31. What's the mental model difference between lifecycle methods and useEffect? Complete this sentence: "useEffect doesn't react to lifecycle events — it ___."
Q32. Write three useEffect calls demonstrating: (a) runs every render, (b) runs once on mount, (c) runs when userId changes.
Q33. When exactly does useEffect fire relative to DOM update and browser paint?
Q34. What does the cleanup function return from useEffect do? When does it run? (Two occasions.)
Q35. Write a useEffect that adds a resize event listener with proper cleanup.
Q36. Why can't you make the useEffect callback async? What does React expect the return value to be?
Q37. Show two patterns for handling async operations inside useEffect.
Q38. What is the "stale closure" problem? Write a counter with setInterval that demonstrates it, then fix it using the updater function pattern.
Q39. How does React compare dependency array values between renders? What comparison function does it use?
Q40. Why does useEffect(() => {...}, [{ id: 1 }]) re-run on every render even if the object value hasn't changed?
Q41. What is the difference between useEffect and useLayoutEffect? When should you use useLayoutEffect?
Q42. In React Strict Mode (development), effects run twice. Why does React do this? Should you "fix" it by removing Strict Mode?
Q43. Write a useEffect with separation of concerns: one for data fetching and a separate one for document title — both depending on pageId.
Q44. What does the react-hooks/exhaustive-deps ESLint rule enforce? Give an example of "lying" about dependencies.
Q45. List three things you should NOT use useEffect for. What should you use instead?
2.4.d — Data Fetching, Cleanup & DOM (Q46–Q60)
Q46. Write a complete fetch-in-useEffect pattern with: loading state, error state, AbortController cancellation, and non-OK HTTP handling.
Q47. Explain the race condition bug when a user types quickly in a search box that triggers fetches. How does AbortController prevent it?
Q48. What is the ignore flag pattern? When would you use it instead of AbortController?
Q49. Build a useFetch(url) custom hook that returns { data, loading, error } with proper cancellation.
Q50. What is useRef used for? Name both use cases (DOM reference and mutable variable).
Q51. Write a component that auto-focuses an input on mount using useRef.
Q52. When should you use useLayoutEffect instead of useEffect for DOM measurement? Give a concrete scenario where useEffect would cause a visual flicker.
Q53. Write a useElementSize hook that tracks an element's width and height using ResizeObserver.
Q54. Write an infinite scroll hook using IntersectionObserver.
Q55. How would you integrate Chart.js with React? Show the pattern for: (a) creating the chart on mount, (b) updating data, (c) destroying on unmount.
Q56. Write a WebSocket connection hook with: connect on mount, auto-reconnect with exponential backoff, and close on unmount.
Q57. Build a useLocalStorage(key, initialValue) hook that also syncs across browser tabs using the storage event.
Q58. Explain the data fetching evolution in React: useEffect → TanStack Query → Server Components. What problem does each solve?
Q59. Write a focus trap for a modal that: (a) captures focus on open, (b) traps Tab/Shift+Tab, (c) restores focus on close.
Q60. Create a cleanup checklist: for each setup type (setInterval, addEventListener, fetch, WebSocket, IntersectionObserver), write the corresponding cleanup call.