What is useRef in ReactJS, for example?

What is useRef in ReactJS, for example?

In React.js, theuseRef hook is used to create mutable object properties that persist across renders without causing re-renders when the value changes. It's often used to get a reference to a DOM element or to persist values between renders without triggering a re-render.

Here's a simple example of using useRef:

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

function ExampleComponent() {
  // Create a ref object
  const myRef = useRef(null);

  // useEffect to focus on the input element when the component mounts
  useEffect(() => {
    myRef.current.focus();
  }, []);

  return (
    <div>
      {/* Attach the ref to the input element */}
      <input ref={myRef} type="text" />
    </div>
  );
}

export default ExampleComponent;

In this example:

  1. We import useRef from the React library.

  2. We create a ref object using const myRef = useRef(null);.

  3. We attach this ref to an input element using the ref attribute: <input ref={myRef} type="text" />.

  4. We use the useEffect hook to focus on the input element when the component mounts. The useEffect hook runs after the initial render.

Here's a breakdown:

  • useRef(null)creates a ref object with an initial value of null.

  • The ref is attached to the input element, making myRef.current refer to the input DOM node.

  • In the useEffect hook, when the component mounts ([] as the dependency array), it calls myRef.current.focus(), focusing on the input element.

Conclusion:

The key point here is that changes to the ref object (myRef.current) don't cause the component to re-render. This makes useRef useful for holding mutable values that persist across renders without triggering unnecessary re-renders.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!