Understanding Useref & Its Implementation

In the realm of React, hooks have transformed the approach to state and side effect management. Among these hooks, useRef stands out as particularly beneficial yet often overlooked. useRef permits the creation of a mutable reference to a DOM element or any other value that remains consistent across renders. In this blog post, we'll delve into the concept of useRef, its utilization, and explore diverse scenarios where it can serve as a potent tool.

Grasping the Concept of useRef

useRef, a React-provided Hook, is frequently utilized for accessing and manipulating DOM elements. Additionally, it serves the purpose of preserving values between renders without triggering re-renders.

Here's a straightforward illustration of employing useRef:

import React, { useRef, useEffect } from 'react';
function MyComponent() {
  const myRef = useRef();
  useEffect(() => {
    myRef.current.focus();
  }, []);
  return (
    <input ref={myRef} />
  );
}

In the provided code, we utilize the useRef hook to generate a myRef and link it to the input element through the ref prop. Additionally, we employ the useEffect hook to prioritize focus on the input element upon component mounting. This scenario exemplifies a typical application of useRef in managing DOM elements.

Utilizations of useRef

1. Handling focus and text selection

As demonstrated in the preceding example, useRef proves useful in directing focus to input fields or overseeing text selection. This functionality greatly enhances user interactions in forms or input areas, particularly when paired with complementary hooks such as useEffect.

2. Initiating imperative animations

Referring to useRef, you can activate imperative animations or interactions. For instance, you may wish to programmatically initiate or halt a video, display or conceal a modal, or toggle a drawer's visibility. By establishing a reference to the DOM element, you can directly manage these interactions without necessitating state alterations.

import React, { useRef } from 'react';
function VideoPlayer() {
  const videoRef = useRef();
  const playVideo = () => {
    videoRef.current.play();
  }
  const pauseVideo = () => {
    videoRef.current.pause();
  }
  return (
    <div>
      <video ref={videoRef} src="my-video.mp4"></video>
      <button onClick={playVideo}>Play</button>
      <button onClick={pauseVideo}>Pause</button>
    </div>
  );
}

3. Retaining Previous Values

In certain scenarios, it's necessary to contrast the current value of a prop or state with its prior value. This proves beneficial when actions need to be executed based on value alterations, like initiating a network request upon a specific data change. Such functionality can be attained through useRef.

import React, { useState, useEffect, useRef } from 'react';
function DataComponent({ data }) {
  const prevDataRef = useRef();
  useEffect(() => {
    if (prevDataRef.current !== data) {
      // Data has changed, perform an action
      console.log('Data has changed:', data);
    }
    // Update the ref with the current data for the next comparison
    prevDataRef.current = data;
  }, [data]);
  return <div>{data}</div>;
}

In this instance, we employ prevDataRef to retain the previous value of the data prop, subsequently comparing it within the useEffect to identify alterations.

4. Personalized Caching

Using useRef, you have the ability to devise tailored caching mechanisms. For instance, if you possess a computationally intensive function that consistently yields the same outcome for identical inputs, caching the results can circumvent the need for recalculations during each render.

import React, { useRef } from 'react';
function ExpensiveCalculation() {
  const resultCache = useRef({});
  const calculate = (input) => {
    if (!resultCache.current[input]) {
      // Perform the expensive calculation
      resultCache.current[input] = /* result */;
    }
    return resultCache.current[input];
  }
  return <div>{calculate(someInput)}</div>;
}

Through storing the computed outcomes in resultCache, you mitigate redundant computations, thereby enhancing performance.

In summary

useRef, a multifaceted hook in React, extends its utility far beyond mere DOM interaction. Its capabilities encompass focus management, animation triggering, previous value comparison, and even bespoke caching mechanisms. It stands as a valuable asset within your React arsenal, adept at efficiently addressing a spectrum of challenges.

This blog delved into the useRef hook, offering code samples and showcasing its various applications. Armed with an understanding of useRef's functionality and its potential applications, you can elevate your React projects by leveraging its capabilities to craft more dynamic and streamlined user interfaces.

Creating Responsive Grid Layouts Using Gridstack