Dev.to WebDev 🛠 Dev 👁 0 📖 1 min read

useRef in React

What is useRef? useRef is a React Hook that allows us to create a mutable reference that persists across component re-renders. Unlike useState, updating a useRef value does not cause the component to re-render. Synt

What is useRef?

  • useRef is a React Hook that allows us to create a mutable reference that persists across component re-renders.
  • Unlike useState, updating a useRef value does not cause the component to re-render.

Syntax

const refName = useRef(initialValue);

Importing useRef

import { useRef } from "react";

Why Do We Use useRef?

The useRef Hook is mainly used for:

  • Accessing and manipulating DOM elements directly.
  • Storing values that should persist between renders.
  • Keeping track of previous values.
  • Managing timers and intervals.

Example 1: Accessing an Input Element

import React, { useRef } from "react";

function App() {
  const inputRef = useRef();

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

  return (
    <>
      <input type="text" ref={inputRef} />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}

export default App;

How it Works

  • useRef() creates a reference object.
  • The reference is attached to the input using the ref attribute.
  • inputRef.current points to the actual DOM element.
  • Calling focus() places the cursor inside the input box.

Example 2: Storing a Value Without Re-rendering

import React, { useRef } from "react";

function Counter() {
  const countRef = useRef(0);

  const increment = () => {
    countRef.current++;
    console.log(countRef.current);
  };

  return (
    <button onClick={increment}>
      Increment
    </button>
  );
}

Explanation

  • The value is stored in countRef.current.
  • Updating it does not trigger a component re-render.
  • Useful when a value needs to be remembered but doesn't need to be displayed on the screen.
📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.