useRef: Values That Don't Re-render

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

What you'll learn

UseRef.jsx

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>
  );
}

Step by step

  1. React renders <ClickCounter> for the first time: it calls the ClickCounter function.
  2. useState runs for the first time, so React stores the starting value for shown and returns it: 0.
  3. useRef(0) creates { current: 0 }. React keeps the same object for every render.
  4. useRef creates a ref object, { current: null }. React keeps the same object for every render.
  5. ClickCounter returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  6. After the page is built, React puts the real <input> element into inputRef.current.
  7. You click the “Count” button. React calls its onClick handler.
  8. clicks.current is now 1, but nothing renders: the page still says 0.
  9. You click the “Count” button. React calls its onClick handler.
  10. clicks.current is 2. Still no render.
  11. You click the “Show” button. React calls its onClick handler.
  12. setShown(clicks.current) queues shown = 2.
  13. inputRef.current.focus() puts the cursor in the real input, outside React's rendering.
  14. React renders <ClickCounter> again (render 2): it calls ClickCounter once more, from the top.
  15. useState returns the value React has kept for shown: 2. The starting value is only used on the first render.
  16. useRef returns the same ref object as last time: { current: 2 }.
  17. useRef returns the same ref object as last time: { current: <input> element }.
  18. ClickCounter returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  19. Now the page shows 2.

Common mistakes

Best practices

Key takeaways

Check yourself

ref.current = 5 causes a re-render?

Answer: No

What is inputRef.current after the first render?

Answer: The <input> element. React fills it in when it creates the element.

·

More in Effects and Refs