React.js hooks: useRef

When working with React.js, you may come across situations where you need to get direct access to a DOM element or a variable that persists across re-renders. This is where the useRef hook comes into play.

What is useRef?

useRef is a built-in hook in React.js that returns a mutable ref object. It can be used to persist values between React component renderings without causing a re-render.

How to Use useRef?

To use useRef, you first need to import it from the react package:

import React, { useRef } from 'react';

Next, declare a ref variable within your functional component:

const myRef = useRef();

You can use myRef to hold a reference to a DOM element, a value, or any other data that needs to persist across re-renders.

Accessing DOM Elements with useRef

One common use case of useRef is to get direct access to a DOM element. You can achieve this by attaching the ref attribute to the desired element:

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

  const handleClick = () => {
    inputRef.current.focus();
  };

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

In the example above, the inputRef is used to reference the input element. When the button is clicked, the handleClick function will be called, and it uses inputRef.current to access the DOM element and call the focus method on it.

Persisting Values with useRef

Another useful application of useRef is to persist values across re-renders without triggering a re-render. This can be handy when you need to store variables, flags, or any data that you want to retain between component updates.

const MyComponent = () => {
  const counterRef = useRef(0);

  const incrementCounter = () => {
    counterRef.current += 1;
    console.log(counterRef.current);
  };

  return (
    <div>
      <button onClick={incrementCounter}>Increment Counter</button>
    </div>
  );
};

In the above example, counterRef is initialized with a value of 0 using useRef(0). Every time the button is clicked, the incrementCounter function is called, and it updates the counterRef.current value, which persists across re-renders. The updated value is then logged to the console.

Conclusion

The useRef hook in React.js is a powerful tool that allows you to access DOM elements and persist values without causing re-renders. It comes in handy in various scenarios, such as managing focus, handling animations, or storing mutable data in functional components. By leveraging useRef, you can optimize your React applications and enhance their performance.

#ReactJS #useRef