DEV Community

Cover image for What is useRef in React ?
_Khojiakbar_
_Khojiakbar_

Posted on

What is useRef in React ?

What is useRef in React?

useRef is a hook in React that lets you create a reference to a DOM element or a value that persists across renders without causing re-renders.

Why do we need useRef?

1. Accessing DOM Elements: For directly interacting with DOM elements, like focusing an input field or scrolling to a particular section.
2. Storing Mutable Values: To keep track of values that persist across renders without triggering re-renders, like a counter or a timer.

How to use useRef?

1. Create a Reference: Use useRef to create a reference object.
2. Attach the Reference: Attach the reference to a DOM element or use it to store a value.
3. Access the Reference: Access the reference whenever needed without triggering a re-render.

Funny-Serious Example:

Let's create an example where a button click focuses on an input field and shows how many times a user has tried to "focus" (pun intended) on entering text. Imagine you're a detective trying to crack a secret code, and every time you click the button, you get a little closer to the truth.

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

function DetectiveInput() {
  // Step 1: Create a reference
  const inputRef = useRef(null);
  const attemptCountRef = useRef(0);

  // State for displaying attempt count
  const [attemptCount, setAttemptCount] = useState(0);

  // Function to focus input and update attempt count
  const handleButtonClick = () => {
    // Step 3: Access the reference to focus the input
    inputRef.current.focus();

    // Update attempt count in ref and state
    attemptCountRef.current += 1;
    setAttemptCount(attemptCountRef.current);
  };

  return (
    <div>
      <h1>Detective's Secret Code Input</h1>
      {/* Step 2: Attach the reference to the input element */}
      <input ref={inputRef} placeholder="Enter the secret code..." />
      <button onClick={handleButtonClick}>Focus on Input</button>
      <p>You have attempted to focus {attemptCount} times.</p>
    </div>
  );
}

export default DetectiveInput;
Enter fullscreen mode Exit fullscreen mode

Explanation:

1. Create a Reference:

const inputRef = useRef(null);
const attemptCountRef = useRef(0);
Enter fullscreen mode Exit fullscreen mode

Here, inputRef is a reference to the input element, and attemptCountRef is a reference to keep track of how many times the button has been clicked.
2. Attach the Reference:

<input ref={inputRef} placeholder="Enter the secret code..." />
Enter fullscreen mode Exit fullscreen mode

The ref attribute attaches the inputRef to the input element.

3. Access the Reference::

inputRef.current.focus();
attemptCountRef.current += 1;
setAttemptCount(attemptCountRef.current);
Enter fullscreen mode Exit fullscreen mode

In the handleButtonClick function, inputRef.current.focus() focuses the input element, and attemptCountRef.current += 1 increments the attempt count. setAttemptCount(attemptCountRef.current) updates the state to display the new attempt count.

Funny-Serious Twist:

Imagine you're a detective named "Inspector Ref," and every time you click the button, you're trying to crack the secret code by focusing on the input field. Each click is a new attempt to unveil the mystery. The more attempts you make, the closer you get to solving the case. The UI updates with your current number of attempts, showing how persistent you are in your detective work!

This example combines a bit of fun with a practical demonstration of useRef, showing how you can use it to directly interact with DOM elements and manage mutable values efficiently in a React application.

Top comments (0)