Count clicks in a ref without re-rendering, then show the count and focus an input through a DOM ref.
React · beginner · 7 min · 19 steps · free
import { useState, useRef } from 'react';
export default function ClickCounter() {
const [shown, setShown] = useState(0);
const clicks = useRef(0);
const inputRef = useRef(null);
function countQuietly() {
clicks.current = clicks.current + 1;
}
function showCount() {
setShown(clicks.current);
inputRef.current.focus();
}
return (
<div>
<input ref={inputRef} placeholder="Focus lands here" />
<button onClick={countQuietly}>Count</button>
<button onClick={showCount}>Show</button>
<p>Clicks shown: {shown}</p>
</div>
);
}<ClickCounter> for the first time: it calls the ClickCounter function.useState runs for the first time, so React stores the starting value for shown and returns it: 0.useRef(0) creates { current: 0 }. React keeps the same object for every render.useRef creates a ref object, { current: null }. React keeps the same object for every render.ClickCounter returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.inputRef.current.onClick handler.clicks.current is now 1, but nothing renders: the page still says 0.onClick handler.clicks.current is 2. Still no render.onClick handler.setShown(clicks.current) queues shown = 2.inputRef.current.focus() puts the cursor in the real input, outside React's rendering.<ClickCounter> again (render 2): it calls ClickCounter once more, from the top.useState returns the value React has kept for shown: 2. The starting value is only used on the first render.useRef returns the same ref object as last time: { current: 2 }.useRef returns the same ref object as last time: { current: <input> element }.ClickCounter returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Answer: No
Answer: The <input> element. React fills it in when it creates the element.
← Loading Data in an Effect · useContext: Passing Data Deeply →