What is useRef?
- React course
- Beginner
- Lesson 73/84
- 4 min
Learn to store a value without re-rendering with useRef.
What is useRef?
useRef is a hook that holds a mutable value inside a component. const ref = useRef(0); returns an object like { '{ current: 0 }' }.
The difference from state: changing ref.current does not re-render the component. This is ideal for data that is shared between functions but not shown on screen.
Two typical uses: access a DOM element (input, div, canvas) and remember a value without triggering re-render on change. This lesson focuses on the second.
State vs useRef
useState and useRef both hold values, but the difference is rendering. setCount computes a new value and re-renders; ref.current = 5 just writes the value, no render.
Use state for data shown on screen, ref for data not shown but the code needs to remember. Example: timer id (interval id), previous value, count counter.
They can be used together: pick state when you want a render on change, ref to remember silently.
Practice Create counter ref
Complete the skeleton. Write a Counter component. Add const countRef = useRef(0);. On button click, increment countRef.current and show <p>{ '{ countRef.current }' }</p> (not with state). Initial render shows 0.
Starter code
import { useRef } from "react";
// Write the Counter component hereSample solution
import { useRef } from "react";
function Counter() {
const countRef = useRef(0);
return (
<div>
<p>{countRef.current}</p>
<button onClick={() => { countRef.current++; }}>Increment</button>
</div>
);
}
export default Counter;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does useRef trigger a render?
- On first call
- On every change
- Never Correct answer
- On every render
Explanation: useRef never triggers a render.
2 useRef access
The value held by useRef is read via ____.
The value held by useRef is read via current.
Explanation: You access the value via ref.current.
3 Match the useRef concepts
| Term | Meaning |
|---|---|
useRef |
Holds value |
current |
Access property |
State |
Triggers render |
DOM |
Element access |