Exploring React Hooks: useRef

Exploring React Hooks: useRef

Exploring the power of useRef Hook in React

Welcome back to our Exploring React Hooks series! In our previous articles, we have explored the useContext Hook. Today, we will explore another powerful hook called useRef.

Let's begin..!!

🪝What is the useRef Hook?

The useRef hook is a built-in hook provided by React that allows you to create mutable references to elements or values in functional components.

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

Unlike state variables, which cause a component to re-render when updated, changing the value of the ref does not trigger a re-render of the component.

Syntax and Usage:

const ref = useRef(initialValue)

useRef(initialValue) accepts one argument as the initial value and returns a reference (aka ref).

When you create a ref using the useRef hook, you get a ref object with a current property. This current property holds the value of the reference and persists across re-renders of the component.

  • reference.current : accesses the reference value.

  • reference.current = newValue : updates the reference value.

The useRef Hook can be used to reference DOM elements, store previous values, manage focus, create timers, and much more.

Rules about References:

  1. The value of the reference is persisted (remains unchanged) between component re-renderings.

  2. Updating a reference doesn't trigger a component re-rendering.

🪝Scenario 1: Accessing DOM Elements

🔈Let's say we have a scenario where we have to automatically focus on the input field when the component is rendered for the first time.

We would need to access DOM elements, for example, to focus on the input field when the component mounts.

🔊 Let's create a component called AutoFocusInput. Inside the component, we will import the useRef Hook and then initialize a ref object called inputRef using the useRef() hook. We would use this ref object to reference one of the input elements in the DOM.

We will then be using the useEffect hook to perform a side effect: focus the input element when the component mounts. This is achieved by accessing the DOM element using inputRef.current and calling the focus() method on it.

import React, { useRef, useEffect } from "react";

const AutoFocusInput = () => {
  const inputRef = useRef();

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return (
    <>
      <div>
        <label htmlFor="name">Name:</label>
        <input type="text" id="name" />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input type="text" id="email" ref={inputRef} />
      </div>
    </>
  );
};

export default AutoFocusInput;

The rendering output consists of two div containers:

  • The first div contains a label element with the text "Name:" and an input element with the type text.

  • The second div contains a label element with the text "Email:" and an input element with the type text and the ref attribute set to inputRef.

This allows the input element inside the second div to be referenced by inputRef and receive focus through the useEffect hook.

Output:

As you can see, this component renders two input fields, with the second input field automatically receiving focus when the component is mounted.

🪝Scenario 2: Tracking State Changes

The useRef Hook can also be used to keep track of previous state values.

🔈Let's say we have another scenario where we have to keep track of the current and previous values of an input field.

🔊 Let's create a component named TrackState. We will initialize the state variable inputValue using the useState hook, which will represent the current value of the input field. Its initial value is an empty string. We'll also create the setInputValue function to update the value of inputValue.

Next, we will create a ref called previousInputValue using the useRef hook. This ref will store the previous value of the input field. Initially, we'll set it to an empty string.

We'll utilize the useEffect hook. Inside the effect, we will update the value of previousInputValue.current to be equal to the current value of inputValue. This will ensure that previousInputValue.current always holds the previous value of the input field.

import { useState, useEffect, useRef } from "react";

function TrackState() {
  const [inputValue, setInputValue] = useState("");
  const previousInputValue = useRef("");

  useEffect(() => {
    previousInputValue.current = inputValue;
  }, [inputValue]);

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        placeholder="Type Something.."
      />
      <h2>Current Value: {inputValue}</h2>
      <h2>Previous Value: {previousInputValue.current}</h2>
    </>
  );
}

export default TrackState;

The rendering output consists of an <input> element, whose value attribute is bound to the inputValue state variable, and the onChange event handler updates the inputValue with the new value entered by the user.

Below the input field, we display two <h2> elements. The first one shows the current value of the input field using {inputValue}. The second one displays the previous value of the input field using {previousInputValue.current}

Output:

As you can see, the component allows users to type in the input field and see the current value displayed. Additionally, it also displays the previous value, which gets updated whenever the user modifies the input.

🪝Benefits and Use Cases of useRef:

  1. Referencing DOM elements:

    useRef is commonly used to reference DOM elements within functional components, allowing access to their properties and methods.

  2. Storing previous values:

    useRef can be used to store values that need to persist across re-renders, such as previous state values or props, enabling comparisons and conditional actions.

  3. Managing focus:

    useRef is useful for managing focus within a component, enabling tracking and manipulation of focus on input fields, buttons, or other interactive elements.

  4. Creating timers and subscriptions:

    useRef can store timers, interval IDs, or subscriptions, ensuring their persistence even during component re-renders.

To Summarize

The useRef hook is a valuable addition to the React Hooks library, allowing us to create mutable references to elements or values.

It provides a simple and efficient way to access and manipulate DOM elements, store previous values, manage focus, and handle other scenarios that involve mutable references.


References


Thank you for taking the time to read this blog. Hope you found it informative and enjoyable!

Do share your thoughts and fell free to connect with me on Twitter.

Stay tuned for our next article, where we'll explore another essential hook: useReducer Hook!

Catch you guys on the next one. Cheers .. ✌️

r

Did you find this article valuable?

Support Raj Sarkar by becoming a sponsor. Any amount is appreciated!