DEV Community

Rakshambika
Rakshambika

Posted on

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.

Syntax

const refName = useRef(initialValue);
Enter fullscreen mode Exit fullscreen mode

Importing useRef

import { useRef } from "react";
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)