- Home
- /
- Tutorials
- /
- React Tutorial
- /
- useRef Explained
Effects and Refs
useRef Explained
A ref is a box that survives re-renders and does not trigger them. That second half is the whole difference from state.
State versus ref
Both keep a value between renders. Changing state schedules a re-render; changing a ref does not, so the screen will not update until something else causes one.
Only one of them updates the screen
jsx
function Compare() {
const [stateCount, setStateCount] = React.useState(0)
const refCount = React.useRef(0)
return (
<div>
<p>State: {stateCount} — Ref: {refCount.current}</p>
<button onClick={() => setStateCount(stateCount + 1)}>Bump state</button>{" "}
<button onClick={() => { refCount.current++ }}>Bump ref (no re-render)</button>
<p style={{ color: "#64748b" }}>
Press the ref button several times — nothing changes. Then press the state
button once and the ref's real value appears.
</p>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<Compare />)