useRef hook in React

In React, the useRef hook allows us to preserve values between re-renders of a component. It returns a mutable ref object which can hold a mutable value.

Usage

To use the useRef hook, we first need to import it from the React library:

import React, { useRef } from 'react';

Next, within our functional component, we can declare a variable using the useRef hook:

const myRef = useRef();

We can then attach this ref to a DOM element or any other value we want to preserve.

Handling DOM elements

The most common use case for useRef is to reference DOM elements. Let’s see an example:

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

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

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

  return (
    <div>
      <input ref={inputRef} type="text" />
    </div>
  );
}

In the above example, we create a ref using useRef and assign it to the ref prop of the input element. This allows us to access the DOM node using inputRef.current. In the useEffect hook, we call the focus method on the current property to give the input element focus when the component mounts.

Other use cases

useRef can be used for more than just referencing DOM elements. Here are a few other use cases:

Preserving previous values

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

function MyComponent() {
  const previousCountRef = useRef();
  const count = 0;

  useEffect(() => {
    previousCountRef.current = count;
  });

  return (
    <div>
      <p>Previous Count: {previousCountRef.current}</p>
      <p>Current Count: {count}</p>
    </div>
  );
}

In this example, we use useRef to store the previous value of count and display it in the component.

Storing mutable values without causing re-render

import React, { useRef } from 'react';

function MyComponent() {
  const renderCount = useRef(0);

  renderCount.current += 1;

  return (
    <div>
      <p>Render Count: {renderCount.current}</p>
    </div>
  );
}

Here, we use useRef to store a mutable value (renderCount) that doesn’t cause the component to re-render when it changes. This can be useful for tracking certain values without triggering unnecessary re-renders.

Conclusion

The useRef hook in React is a powerful tool for preserving values between re-renders. Whether it’s referencing DOM elements or storing mutable values, useRef allows us to work with mutable values in a functional component. It’s a handy addition to React’s hooks API.

#React #ReactHooks