Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.
Exercise 1 of 2
Five real scenarios. For each one, decide whether you need useRef or useState β and understand the one question that makes the choice obvious.
For each scenario, choose useRef or useState. Ask yourself: does a change here need to update the UI?
Storing the previous value of a prop so you can compare it in the render output.
Tracking whether a user has submitted a form β shown as a checkmark in the UI.
Holding a setInterval ID so you can clear it when the component unmounts.
A search query string that filters a visible list as the user types.
A reference to a DOM input element so you can call .focus() programmatically.
0/5 answered
π‘ Decision rule: if changing the value must update what the user sees, use useState. If it is invisible to the user or you only need it between renders without triggering one, use useRef.
Exercise 2 of 2
Live editor: implement a usePrevious custom hook using useRef + useEffect. Returns the value from the last render without causing extra re-renders.
Task
Implement usePrevious(value) β a custom hook that returns the value from the previous render. Click +1 or -1 and both current and previous counts should display.
You need a useRef to persist the value across renders without triggering one, and a useEffect to update it after the render completes.