In this article I am going to discuss about the useRef hook in react but before that if you have not read the previous articles of different type of hooks then you can go through them if you have any doubt in any of the hooks. So the useRef hook is used to create mutable object properties that persist across renders. Unlike useState, changes to a ref object do not trigger a re-render of the component. useRef is often used to access and interact with the DOM directly, manage focus, or to keep a reference to a value that persists between renders without causing re-renders.

When to use the useRef hook?

Basically, react handle all DOM manipulation by themselves , But there are some instances where useRef can be used without causing issues. In React, we can add a ref attribute to an element to access it directly in the DOM. We can initialize the useRef like this, we can also pass null to useRef.

const count = useRef(0);

How to use useRef hook?

Let see a simple example of how we can use the useRef hook:

import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const [inputValue, setInputValue] = useState("");
  const count = useRef(0);

  useEffect(() => {
    count.current = count.current + 1;
  });

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h1>Render Count: {count.current}</h1>
    </>
  );
}

Above is the simple example we can use the useRef hook. Remember it does not re-render when the value changes. There is one more example discussed below which tells how we can focus the element with useRef hook.

import { useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const inputElement = useRef();

  const focusInput = () => {
    inputElement.current.focus();
  };

  return (
    <>
      <input type="text" ref={inputElement} />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}

If you want to know more about the useRef hook then you can go through the official documentation of react. Now this is all about the useRef mostly we have covered all the react hooks. The only hook remaining is useId that is very simple to use and this is only used to generate random ids. Like discussed in the below code:

How to use the useId hook in react?

import { useId } from 'react';

function PasswordField() {
  const passwordHintId = useId();
  return (
    <>
      <label>
        Password:
        <input
          type="password"
          aria-describedby={passwordHintId}
        />
      </label>
      <p id={passwordHintId}>
        The password should contain at least 18 characters
      </p>
    </>
  );
}

Conclusion

Above is the simple code which demonstrates how we can use the useId for generating random Ids for our react elements. Remember it is always the good practice to give unique keys to your react elements.