← React Beginner Questions - Set 2 Q19

What is the purpose of the useRef hook?

React Beginner Questions - Set 2

A ref is a mutable box that survives renders and never triggers one. This example uses it for both jobs a ref has.

Example

import { useRef, useState } from 'react';

export default function Search() {
  const inputRef = useRef(null);      // DOM reference
  const rendersRef = useRef(0);       // mutable value, no re-render

  const [, forceRender] = useState(0);
  rendersRef.current += 1;

  return (
    <div>
      <input ref={inputRef} placeholder="Type here" />
      <button onClick={() => inputRef.current.focus()}>Focus</button>

      <p>Renders so far: {rendersRef.current}</p>
      <button onClick={() => forceRender(n => n + 1)}>Re-render</button>
    </div>
  );
}

What to notice

← Back to the question list