0
0
ReactConceptBeginner · 3 min read

What is useRef in React: Simple Explanation and Example

useRef is a React hook that lets you keep a mutable value that does not cause re-render when changed. It is often used to access DOM elements directly or to store any value that persists across renders without triggering updates.
⚙️

How It Works

Imagine you have a box where you can store something, and you want to keep it safe between visits to your room without changing the room's setup. useRef gives you that box in React. It holds a value in its current property, and this value stays the same even if the component updates.

Unlike state, changing the value inside this box does not make React redraw the screen. This is useful when you want to keep track of something behind the scenes, like a timer ID or a reference to a button on the page, without causing the whole component to refresh.

💻

Example

This example shows how to use useRef to focus an input box when a button is clicked.

javascript
import React, { useRef } from 'react';

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

  const handleFocus = () => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <div>
      <input ref={inputRef} type="text" placeholder="Click the button to focus me" />
      <button onClick={handleFocus}>Focus Input</button>
    </div>
  );
}

export default FocusInput;
Output
An input box and a button appear. Clicking the button moves the cursor focus into the input box.
🎯

When to Use

Use useRef when you need to keep a value that should not trigger a re-render when it changes. Common cases include:

  • Accessing or controlling DOM elements directly, like focusing an input or measuring size.
  • Storing mutable values such as timers, intervals, or previous state values.
  • Keeping any data that persists across renders but does not affect the UI directly.

For example, if you want to remember the last scroll position or keep a count that updates without refreshing the screen, useRef is a good choice.

Key Points

  • useRef returns a mutable object with a current property.
  • Changing current does not cause the component to re-render.
  • It can hold any value, including DOM nodes or simple data.
  • Useful for accessing DOM elements or storing values across renders.

Key Takeaways

useRef stores a value that persists across renders without causing re-renders.
It is commonly used to access DOM elements directly in React components.
Changing the current property does not update the UI automatically.
Ideal for storing mutable values like timers or previous state references.
Helps keep data between renders without affecting component performance.