BP217: Use the useRef hook to access DOM elements or store mutable values

Use the useRef hook to access DOM elements or store mutable values in functional components. The useRef hook is a built-in React hook that allows you to create a mutable reference that persists across re-renders. This is useful for accessing DOM elements, managing focus, or storing mutable values that don't trigger a re-render when they change.

One common use case for useRef is to access DOM elements. In class components, you would typically use the ref attribute to create a reference to a DOM element. However, in functional components, you can use the useRef hook to achieve the same result. For example, you might use useRef to create a reference to an input element and then use that reference to focus the input when a button is clicked:

import React, { useRef } from 'react';

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

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

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

Another use case for useRef is to store mutable values that don't trigger a re-render when they change. For example, you might use useRef to store a timer ID that you want to clear when the component unmounts:

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

function MyComponent() {
  const timerIdRef = useRef(null);

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

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

  return <div>Hello, world!</div>;
}

In this example, we create a mutable reference called timerIdRef using the useRef hook. We then use useEffect to set up an interval that logs "Tick" to the console every second. We store the ID of the interval in timerIdRef.current so that we can clear it when the component unmounts.

Comments

No Comments Yet.
Be the first to tell us what you think.

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play