codewithjohn.dev
Published on

Exploring the Power of React useRef() Hook

Table of Contents

In React, Hooks are unique functions that allows developers to utilize state and other React features without needing class components.

In this post we will explore how to use React.useRef() hook to create persisted mutable values (also known as references or refs). we will also explore useRef() ability to access and manipulate DOM elements.

What Is the useRef Hook?

In React, manipulating and accessing DOM elements directly can be difficult but with the help of the useRef() hook you can easily obtain a reference to a particular DOM element and perform operations on it.

React useRef() is one of built-in React hook that allows you to access and manipulate DOM elements directly within functional components. Some of the common uses of React useRef() includes to access DOM elements, to manage focus, store previous values, and more.

React useRef() does not trigger a re-render This ref object can be used to persist values across render cycles without triggering a re-render unlike the useState() hook.

Steps to Use useRef in React

Here's a breakdown of the steps involved in using the useRef hook in React:

  1. Import useRef:

Begin by importing the useRef hook from the react library at the top of your functional component file:

import { useRef } from 'react'
  1. Create a useRef Object:

Utilize the useRef hook to establish a ref object. You can optionally provide an initial value within the parentheses:

const myRef = useRef(initialValue) // Example: useRef(null) or useRef(0)
  • If no initial value is specified, the current property within the ref object will be set to null by default.
  1. Assign the Ref to a JSX Element (Optional):

To establish a connection between a functional component and a DOM element, assign the created ref object (e.g., myRef) to the ref attribute within your JSX:

<input type="text" ref={myRef} />
  1. Access the DOM Element (Optional):

After assigning the ref to a JSX element, you can access the corresponding DOM node using the current property of the ref object:

const focusInput = () => {
  if (myRef.current) {
    myRef.current.focus() // Assuming myRef is assigned to an input element
  }
}
  • The if check ensures that the code inside only executes if the DOM element is actually available (i.e., myRef.current is not null).
  1. Storing and Updating Mutable Values:
  • To store a mutable value within the ref object, utilize the current property:

    countRef.current = someValue
    
  • Modifying current does not trigger re-renders as it's not directly tied to the component's state.

Core Functionalities of useRef

Creating DOM Element References:

useRef grants you the ability to establish a connection between a functional component and a DOM element. By assigning the ref object to the ref attribute within JSX, React assigns the corresponding DOM node to the current property of the ref object.

import React, { useRef } from 'react'

function InputField() {
  const inputRef = useRef(null)

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

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

In this example, useRef creates a ref object (inputRef). Assigning it to the ref attribute of the <input> element establishes a link. Clicking the button triggers the focusInput function, which in turn utilizes inputRef.current.focus() to bring focus to the input field.

Persisting Mutable Values:

Unlike component state, which triggers re-renders on modification, useRef offers a way to store mutable values (values that can change) without causing re-renders. This is particularly valuable for scenarios where you require a value to persist across renders without affecting the UI.

import React, { useRef } from 'react'

function Counter() {
  const countRef = useRef(0)

  const increment = () => {
    countRef.current++
  }

  return (
    <div>
      <p>Count: {countRef.current}</p>
      <button onClick={increment}>Increment</button>
    </div>
  )
}

Here, useRef is employed to create a countRef object initialized to 0. The increment function increments the value stored in countRef.current without causing a re-render, as the UI display (the <p> element) doesn't rely on the ref directly.

Conclusion

Although React normally takes care of updates on its own, useRef is like a secret weapon in your React components. It lets you interact directly with parts of the screen, hold onto values that can change without slowing things down, and manage things like focus. This extra control makes your React applications more powerful and responsive, providing a smoother experience for your users.