HomeBlogsProjectsBookmarksPoemsImagesAboutFeedbackAdmin

How to use useRef in React?

useRef is a React Hook that lets you reference a value that’s not needed for rendering.

19th March, 2024
5 min read
ReactJs
How to use useRef in React?

Introduction

React provides a variety of hooks that empower developers to manage state and interact with the DOM efficiently. One such hook is useRef, which allows you to create a mutable reference to a DOM element or any mutable value that persists across renders without causing re-renders. In this guide, we'll explore how to effectively utilize useRef in React applications.

What is useRef?

useRef is a hook provided by React that returns a mutable ref object whose useRef property is initialized with the passed argument. The useRef property can be assigned a value, and it persists between renders. Unlike state, updating the ref value doesn't trigger a re-render.

When to Use useRef?

  • Accessing DOM elements: You can use useRef to gain direct access to DOM elements and interact with them imperatively.
  • Storing mutable values: useRef can store mutable values that persist across renders, useful for keeping track of values without causing re-renders.
  • Preserving values between renders: Unlike local variables, values stored in refs are preserved between renders.

Basic Usage

import React, { useRef } from 'react';

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

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

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


console.log("Hello world");