1. Home
ReactJS

ReactJS Tutorial: A Comprehensive Guide

Master ReactJS with our in-depth tutorials. From beginner to advanced topics, explore essential concepts and build dynamic web applications effortlessly.

  • 10
  • 3
right-top-arrow
9

Mastering useRef In React: A Detailed Guide

Updated on 06/09/2024428 Views

Introduction

useRef is a React.js hook that lets you create a mutable reference to a value or element. Since its introduction, useRef has become very useful in the React developer's toolkit.

useRef React provides a straightforward solution for tasks like managing focus in forms, accessing DOM elements directly, and storing values without causing unnecessary re-renders.

This guide will discuss the useRef react applications, best practices, and much more. This will help you understand useRef React like a pro.

Overview

With useRef React, you can effortlessly store mutable values without triggering unnecessary re-renders. This offers a smoother and more efficient user experience. Additionally, useRef provides direct access to DOM elements, thereby improving your ability to interact with the user interface dynamically.

By the end of this guide, you'll have a solid grasp of the useRef hook in React. I will explain its syntax and best practices to use it. We will also discuss practical examples and much more.

What Is useRef In React?

UseRef is a React hook that allows you to reference a value that isn't required for rendering. It allows you to construct a direct reference to the DOM element in the functional component.

The main purpose of the useRef React hook is to access DOM items more efficiently than plain refs. useRef React helps to avoid unwanted re-renders. This is because useRef hooks preserve value over numerous re-renders and do not cause re-renders if a value is updated. This makes the application faster and helps in cache and save prior values.

Now, let's talk about syntax. It's quite simple:

const refContainer = useRef(initialValue);

Let me break it down for you;

useref React hands you a mutable ref object. Inside this object lives a property called current. Whatever value you stash in, current sticks around, even through re-renders. So, whether it's initializing with an initial value or caching previous values, useRef has got your back for the entire lifespan of your component.

useRef React typescript is also quite handy. useRef in React with TypeScript provides a way to create mutable references to elements or values, ensuring type safety and improved code maintenance.

A Simple Example Of How To Use useRef In React

Let's discuss a practical demonstration of how useref React can be used to interact with the DOM directly:

In this useRef React example, we're using useref React to create a reference to an input element. When we click the button, the onClickHandler function is invoked. This function sets the value of the input element to "Hello, world!" and focuses on it, allowing the user to start typing or interacting with the input immediately.

import React from 'react';

const { Fragment, useRef } = React;

function App() {

  // Creating a ref object using useRef hook

  const inputRef = useRef(null);

  const onClickHandler = () => {

    inputRef.current.value = "Hello, world!";

    inputRef.current.focus();

  };

  return (

<Fragment>

   <div>

     <button onClick={onClickHandler}>

       Click Me

        </button>

   </div>

   <label>

     Click the button to focus on the input and populate it.

      </label><br />

   <input type="text" ref={inputRef} />

</Fragment>

  );

};

export default App;

Practical Applications Of useRef In React

Here are some practical application useRef in React you should know.

1. Tracking state changes

useRef React is very handy for tracking changes in state. You can leverage useref React to keep tabs on previous state values, which comes in handy for various scenarios. Since useRef values persist between renders, they serve as an excellent tool for storing historical state data.

Let's look at an example:

const React = require("react");

const { useState, useEffect, useRef } = React;

function App() {

  const [inputValue, setInputValue] = useState("");

  const previousInputValue = useRef("");

  useEffect(() => {

    previousInputValue.current = inputValue;

  }, [inputValue]);

  return (

<>

   <input

        type="text"

        value={inputValue}

     onChange={(e) => setInputValue(e.target.value)}

   />

      <h2>Current Value: {inputValue}</h2>

      <h2>Previous Value: {previousInputValue.current}</h2>

</>

  );

}

export default App;

In the useRef React example above, useRef helps us keep track of the previous value of an input field. Whenever the input value changes, the useEffect hook updates the previousInputValue.current to store the previous value.

2. Referencing And Accessing DOM Elements Directly

Another powerful application of the useRef hook in React is accessing and referencing DOM elements directly. This capability comes in handy when you need to perform operations like focusing on an input field or measuring the dimensions of an element.

Here's a step-by-step breakdown:

  • Define the reference for accessing the element: const elementRef = useRef().
  • Assign a reference to the element's ref attribute:
  • After mounting, element Ref.current points to the DOM element.

Here is an example of how to access and reference DOM elements directly with useRef React.

import { useRef, useEffect } from 'react';

function AccessingElement() {

  const elementRef = useRef();

  useEffect(() => {

const divElement = elementRef.current;

    console.log(divElement); // logs <div>I'm an element</div>

  }, []);

return (

<div ref={elementRef}>

   I'm an element

</div>

  );

}

In the example above, we create a ref to a div element. Upon mounting, the useEffect hook logs the div element referenced by elementRef.current. This capability enables direct interaction with DOM elements within your React components, facilitating smoother user experiences.

3. Managing Focus In Forms And Input Fields

Let’s say you're building a form where you need to focus on a particular input field when the user clicks a button. Instead of querying the DOM each time the button is clicked, useRef enables you to store a reference to that input field and access it directly. This not only streamlines your code but also enhances performance by avoiding unnecessary re-renders.

Let's take a look at an example:

import React, { useRef } from 'react';

function MyForm() {

  const inputRef = useRef();

  const handleClick = () => {

inputRef.current.focus();

  };

  return (

<div>

   <input ref={inputRef} type="text" />

   <button onClick={handleClick}>Focus Input</button>

</div>

  );

}

In this code snippet, useRef is employed to create a reference to the input element. When clicking the button, it triggers the handleClick function, focusing on the input without causing a re-render.

4. Tracking Component Mounts And Unmounts

useref React comes in handy for keeping track of component mounts and unmounts. You can utilize useref React to store flags or state values that persist between renders, providing insight into the component's lifecycle. Here is an example:

import { useRef, useEffect } from 'react';

function MyComponent() {

  const isMounted = useRef(false);

useEffect(() => {

isMounted.current = true;

return () => {

      isMounted.current = false;

};

  }, []);

// Rest of your component logic

}

Advanced Techniques With useRef

useRef React can also be used for more advanced operations. Here are some advanced techniques you should know:

1. Storing Mutable Values Without Triggering Re-renders

An advanced technique and practical use of useRef in React js is to store mutable values without causing re-renders. This is beneficial for scenarios where you need to retain data across renders without impacting the rendering process. Here is an example:

import { useRef } from 'react';

function MyComponent() {

  const mutableValue = useRef(initialValue);

// Update mutableValue.current as needed

  const handleClick = () => {

    mutableValue.current = newValue;

// Perform actions with the updated value

  };

return (

<div>

   {/* Your JSX */}

   <button onClick={handleClick}>Update Value</button>

</div>

  );

}

In the example above , mutableValue is a mutable reference initialized with useRef. You can update its .current property without causing a re-render. This can be useful for managing data that needs to persist across renders but doesn't affect the component's UI directly.

2. Using useRef for Animation and Transitions

useref React is also a great tool for managing animations and transitions in your React applications. By storing mutable values and accessing them directly, you can create smooth and efficient animations without causing unnecessary re-renders. Here is an example:

import { useRef, useEffect } from 'react';

function AnimatedComponent() {

  const animationRef = useRef(null);

  useEffect(() => {

const animate = () => {

   // Perform animation using animationRef.current

};

// Trigger animation on component mount

animate();

return () => {

   // Cleanup animation on component unmount

};

  }, []);

  return (

<div ref={animationRef}>

   {/* Your animated content */}

</div>

  );

}

Comparing useRef, useEffect, And useState

useRef, useEffect, and useState are three important React hooks you should know about. useEffect and useState are similar to useRef React. But they are also very different. Here's a comparison table between useref React, useEffect, and useState:

Feature

useRef

useEffect

useState

Definition

A React hook is used to create mutable references that persist between renders without triggering re-renders.

A React hook is primarily used for executing side effects after rendering, such as data fetching or DOM manipulation.

A React hook is used to manage the component state by storing mutable values that trigger re-renders when changed.

Storing Mutable Values

Store values without re-renders.

Mutable references persist between renders.

Triggers re-render on change.

Accessing DOM Elements

Enables direct access to elements.

Direct access within components.

Indirect access through the state.

Triggering Side Effects

Does not trigger side effects

Triggers side effects after rendering

Does not trigger side effects

Managing Component Lifecycles

Manages to mount and unmount.

Executes code after render, cleans up.

Does not manage life cycles.

Causing Re-renders

Changes do not cause re-renders.

May trigger re-renders depending on the state.

Triggers re-render on change.

useRef Best Practices And Tips

When using useRef, it's essential to follow best practices for optimal performance and maintainability. Follow these tips;

  • Naming conventions and readability: Choose descriptive names for useref React references to enhance code clarity. For example, use inputRef to reference an input element. Clear naming conventions improve understanding and maintainability.
  • Handling null values: Ensure to handle null values appropriately, especially when referencing DOM elements. Always check if the reference is not null before accessing its properties to prevent runtime errors.
  • Managing cleanup: Always remember to clean up references when they are no longer needed to avoid memory leaks. Use useEffect with a cleanup function to perform cleanup operations when the component unmounts. This ensures efficient memory usage and prevents potential issues in your application. 

Conclusion

useRef hook in React js is a very handy tool for managing mutable values and accessing DOM elements efficiently. In different situations such as form control and component life cycle management, useRef React has shown itself to be invaluable.

When you’re familiar with useRef React syntax, and practical use cases of this concept, then you can make the most out of your knowledge about this topic when working on your next project.

Make sure you optimize for performance and maintainability by following proper naming conventions, dealing with null values correctly, and handling cleanup operations, among others. By considering these suggestions, you will be able to utilize the full potential of useref React, leading to sleeker user interfaces powered by more efficient code, which is also less prone to bugs.

FAQs

  1. What is the use of useRef in React?

useRef in React allows you to create mutable references to elements or values that persist between renders. It's commonly used for accessing and managing DOM elements directly, storing persistent values, or working with values that shouldn't trigger a re-render.

  1. What are the best practices of useRef?

Some best practices for useref React include keeping usage consistent, documenting references, testing components, and thinking about the effect of refactoring. 

  1. What is the difference between useRef and ref?

useRef is a hook provided by React for creating mutable references in functional components, while ref is a generic attribute used to reference DOM elements or React components. useref React is typically used within functional components, while ref is used in class components or functional components via useRef.

  1. Why is ref used in React?

Refs in React are used to reference and interact with DOM elements or React components directly. They provide a way to access and manipulate the underlying DOM nodes or React components imperatively.

  1. What is use ref for?

useRef is used in React to create mutable references that persist between renders. It's useful for accessing and managing DOM elements directly, storing values without causing unnecessary re-renders or tracking component mounts and unmounts.

  1. What is a ref type in React?

In React, a ref is a special object that allows you to reference and interact with DOM elements or React components imperatively. It allows you to access and manipulate the underlying DOM nodes or React components directly.

    7.   What is useRef and why is it used?

useRef is a React hook that allows you to create mutable references to elements or values that persist between renders. It can be used for several purposes, such as directly accessing and manipulating DOM elements or holding onto values without having to re-render.

Rohan Vats

Rohan Vats

Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Talk to Career Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...