React useRef Hook

useRef Hook

The useRef hook is one of the various hooks that come with React. This hook allows us to create a reference to the DOM element in a functional component. It also allows us to reference a value not needed during rendering.

The useRef hook accepts a single parameter called the 'initialValue'. It is the value we want the ref's current property to be before rendering. The value is ignored after the initial render.

import { useRef } from 'react';

const Example = () => { 
    const ref = useRef(0); // 0 => initialValue 
}

The useRef hook returns an object with a single property. The property is called 'current'. The value of 'current' is set to 'initialValue' before the initial render. We can later set this property to something else.

import { useRef } from 'react';

export const Counter() { 
let ref = useRef(0);

function handleClick() { 
    ref.current = ref.current + 1; 
    console.log('You clicked ' + ref.current + ' times!'); 
}

return (
    <button onClick={handleClick}>
        Click me!
    </button>
    ) 
}

We can also pass the ref object as a ref attribute to the JSX element. It lets us access DOM elements and even perform DOM manipulation. React will set it as the value of the 'current' property:

const Focus = () => {
  const el = useRef();

  const handleFocus = () => {
    el.current.focus();
  };

  return (
    <>
      <input type="text" ref={el} />
      <button onClick={handleFocus}> Click </button>
    </>
  );
}

Although it is an option to use the useRef hook to perform DOM manipulation, we should mostly let React handle that and use the useRef hook in special instances.

One good thing about the useRef hook is how changing it does not trigger a re-render. It allows us to persist values between renders.

Helpful Resources: