React · Lesson 43 of 120
useRef
Values that don't re-render.
Sometimes you want to remember a value, but changing it shouldn't redraw the page. Like a timer id, or how many times something happened. That's what use ref is for.
- Remember a value
- No re-render
- useRef
Counting without rendering
Clicks is a ref, an object with a current property. Clicking adds one to clicks dot current, and logs it. The page doesn't re-render, so the paragraph still shows zero. We click three times. Run it.
App.jsxjsx
import { useRef } from "react";
export default function App() {
const clicks = useRef(0);
function handleClick() {
clicks.current = clicks.current + 1;
console.log("clicks:", clicks.current);
}
return (
<div>
<p>Shown on the page: {clicks.current}</p>
<button id="b" onClick={handleClick}>Click me</button>
</div>
);
}Output
clicks: 1 clicks: 2 clicks: 3
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#b", "times": 3}]State or ref
Changing state re-renders the component, so use it for what's shown. Changing a ref doesn't, so use it for values the page doesn't show, like timer ids.
useState
- Re-rendersShown on the pagesetX(new)
useRef
- No re-renderBehind the scenesref.current = new
Summary
Use ref remembers values without re-rendering. Next, refs to page elements.
Key takeaways- useRef(0)
- ref.current
- No re-render
Next up: Refs to Elements — focus an input