useRef Beyond DOM Nodes: Mutable Values Without Re-renders

Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.

1

Exercise 1 of 2

useRef or useState?

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?

1

Storing the previous value of a prop so you can compare it in the render output.

2

Tracking whether a user has submitted a form β€” shown as a checkmark in the UI.

3

Holding a setInterval ID so you can clear it when the component unmounts.

4

A search query string that filters a visible list as the user types.

5

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.

2

Exercise 2 of 2

Build usePrevious

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.

Loading editor…
Practice: useRef Beyond DOM Nodes: Mutable Values Without Re-renders β€” Interactive Exercises | Durgesh Rai