React useRef Hook

React is a popular JavaScript library for building dynamic and interactive user interfaces. One of the key features of React is its use of hooks, which are functions that allow developers to use state and other React features within functional components. One such hook is the useRef hook, which allows developers to create a mutable reference to a DOM element or a value that persists across renders.

In this tutorial, we will explore the useRef hook in detail, discussing its use cases, syntax, and benefits.

What is the useRef hook?

The useRef hook is a built-in hook in React that allows developers to create a mutable reference to a DOM element or a value that persists across renders. It returns a mutable object that contains a single property called current, which can be used to store any value. This value will persist across renders and updates to the component.

The useRef hook is often used to access DOM elements and to store values that need to persist across renders, but don’t need to trigger a re-render when they change. For example, you could use the useRef hook to store a timer ID or an instance of an external library.

Syntax of the useRef hook

The syntax of the useRef hook is as follows:

const refContainer = useRef(initialValue);

The useRef hook takes an optional parameter, initialValue, which is the initial value of the current property of the returned object. If no initial value is provided, the current property will be set to undefined.

To access the value of the current property, you can use refContainer.current. You can also assign a new value to the current property directly, like this: refContainer.current = newValue.

Using the useRef hook in practice

One of the most common use cases for the useRef hook is to access DOM elements. To do this, you can create a ref using the useRef hook, and then attach it to the relevant DOM element using the ref attribute. Here’s an example:

import { useRef } from 'react';

function TextInput() {
  const inputRef = useRef();

  function handleClick() {
    inputRef.current.focus();
  }

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

In this example, we create a ref using the useRef hook, and assign it to the ref attribute of the input element. We then define a function called handleClick, which uses the focus method of the input element to give it focus when the button is clicked.

Because the ref is created outside of the component function, it persists across renders and can be used to access the input element even after the component has re-rendered.

Another use case for the useRef hook is to store values that need to persist across renders, but don’t need to trigger a re-render when they change. For example, you could use the useRef hook to store a timer ID, like this:

import { useRef, useEffect } from 'react';

function Timer() {
  const timerIdRef = useRef();

  useEffect(() => {
    timerIdRef.current = setInterval(() => {
      console.log('Tick');
    }, 1000);

    return () => {
      clearInterval(timerIdRef.current);
    };
  }, []);

  return <div>Timer</div>;
}

In this example, we create a ref using the useRef hook, and assign it to the timerIdRef variable. We then use the useEffect hook to set up a timer using the setInterval method. The useEffect hook takes a callback function as its first parameter, which is executed after the component has mounted. We use the timerIdRef.current property to store the ID of the interval so we can clear it when the component unmounts using the clearInterval method.

Note that we pass an empty dependency array [] as the second parameter to useEffect, which means that the effect will only run once when the component mounts, and not again on subsequent renders.

Benefits of using the useRef hook

There are several benefits to using the useRef hook in your React applications:

  1. Accessing DOM elements: The useRef hook provides a convenient way to access DOM elements from within a functional component.
  2. Storing values: The useRef hook allows you to store values that need to persist across renders, but don’t need to trigger a re-render when they change.
  3. Performance optimization: By storing values that don’t need to trigger a re-render in a ref, you can avoid unnecessary re-renders and improve the performance of your application.
  4. Avoiding state updates: Because refs don’t trigger a re-render when their value changes, they can be used to avoid unnecessary state updates.

Conclusion

In this tutorial, we have explored the useRef hook in React, discussing its syntax, use cases, and benefits. We have seen how the useRef hook can be used to access DOM elements and to store values that need to persist across renders. We have also discussed how using the useRef hook can help optimise your React applications’ performance.

By understanding and using the useRef hook effectively, you can create more efficient and maintainable React applications.

Scroll to Top