React useRef Hook

Eman Awad
Nov 20, 2023
1 min read
post_comment0 Comments
post_like0 Likes

useRef hook is a feature in React that allows you to create a mutable object called “ref” . This object can hold a reference to a DOM element or a mutable value in the functional component.

It is commonly used to interact with and manipulate the DOM directly. You can also use useRef to hold mutable values that won't trigger a re-render when they change.

Here's a simple example of how useRef works to interact with and manipulate the DOM directly:


function MyComponent() {
  // Creating a 'myRef ' ref an assign 'null' as default value to it
  const myRef = useRef(null);

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

  // Attaching Ref to a input DOM Element:
  return <input ref={myRef} />;
}

In this example, the myRef ref is linked to the input element via the ref attribute. myRef.current provides direct access to this input in the DOM, enabling us to focus on it when the component mounts.

Here's a simple example of how useRef works to handle a mutable value:

function MyComponent() {
  // Creating a 'count' ref an assign '0' as default value to it
  const count = useRef(0);

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

  return (
    <div>
      <p>Count: {count.current}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
}

In this example, the count ref holds a mutable value (0 initially), and when the button is clicked, it increments the value without triggering a re-render.

📍References :

🔗 React.dev

You are not logged in.