Loading

Quipoin Menu

Learn • Practice • Grow

react / useRef Hook
tutorial

useRef Hook

Imagine you need to directly interact with a DOM element, like focusing an input when a page loads, or you want to store a value that persists across renders but doesn't trigger a re-render when it changes. In React, we have a special hook for this: `useRef`.

What is useRef?

`useRef` is a React Hook that returns a mutable object with a `.current` property. This object persists for the entire lifetime of the component. Changing the `.current` property does **not** cause a re-render.

Think of `useRef` as a box that can hold any value a DOM element, a number, a string, or even an object. React won't notify you when the content of the box changes, but the box itself stays the same across renders.

Common Use Cases for useRef

  • Accessing DOM elements directly (like focusing an input).
  • Storing previous values (e.g., previous state).
  • Keeping mutable values that shouldn't trigger re-renders (e.g., timer IDs).

Example 1: Focusing an Input
import React, { useRef, useEffect } from 'react';

function AutoFocusInput() {
  const inputRef = useRef(null);

  useEffect(() => {
    <!-- Focus the input when component mounts -->
    inputRef.current.focus();
  }, []);

  return <input ref={inputRef} type="text" placeholder="Type here..." />;
}

Example 2: Counting Renders (without causing re-renders)
import React, { useRef, useState, useEffect } from 'react';

function RenderCounter() {
  const [count, setCount] = useState(0);
  const renderCount = useRef(1); <!-- Initial render count -->

  useEffect(() => {
    <!-- Increment on every render -->
    renderCount.current = renderCount.current + 1;
  });

  return (
    <div>
      <p>Button clicked: {count} times</p>
      <p>Component rendered: {renderCount.current} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Example 3: Storing Previous State
import React, { useRef, useState, useEffect } from 'react';

function PreviousValue() {
  const [text, setText] = useState('');
  const previousText = useRef('');

  useEffect(() => {
    previousText.current = text;
  }, [text]);

  return (
    <div>
      <input
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type something"
      />
      <p>Current: {text}</p>
      <p>Previous: {previousText.current}</p>
    </div>
  );
}

Two Minute Drill

  • `useRef` returns a mutable object with a `.current` property that persists across renders.
  • Changing `.current` does **not** cause a re-render.
  • Use it to access DOM elements directly (via `ref` attribute).
  • Use it to store any mutable value that should survive re-renders but not trigger them.
  • Common patterns: focusing inputs, counting renders, storing previous state, keeping timer IDs.

Need more clarification?

Drop us an email at career@quipoinfotech.com