useRef

singhpritpal04

Pritpal Singh

Posted on September 12, 2024

useRef

What is useRef?

The useRef hook in React is used to access and interact with DOM elements directly or to keep a mutable value that does not cause re-renders when changed. It provides a way to persist values across renders without triggering a component update.

How useRef Works

useRef returns a mutable object called a "ref object" with a .current property. This property can hold a value that persists across re-renders.

Basic Syntax

const myRef = useRef(initialValue);
Enter fullscreen mode Exit fullscreen mode
  • initialValue: The initial value for the ref object. This is optional.

Example 1: Accessing DOM Elements

In this example, we'll use useRef to access a DOM element directly.

  1. Create the Component
   import React, { useRef, useEffect } from 'react';

   const FocusInput = () => {
     // Create a ref with useRef
     const inputRef = useRef(null);

     useEffect(() => {
       // Focus the input field when the component mounts
       inputRef.current.focus();
     }, []);

     return (
       <div>
         <input ref={inputRef} type="text" placeholder="Focus me on mount" />
       </div>
     );
   };

   export default FocusInput;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • useRef(null) creates a ref object.
  • inputRef.current gives access to the input element.
  • useEffect is used to focus the input field when the component mounts.

Example 2: Keeping Mutable Values

In this example, we'll use useRef to keep a mutable value that does not cause re-renders when updated.

  1. Create the Component
   import React, { useRef, useState } from 'react';

   const Timer = () => {
     const [count, setCount] = useState(0);
     const timerRef = useRef(null);

     const startTimer = () => {
       if (timerRef.current) {
         clearInterval(timerRef.current);
       }
       timerRef.current = setInterval(() => {
         setCount(prevCount => prevCount + 1);
       }, 1000);
     };

     const stopTimer = () => {
       if (timerRef.current) {
         clearInterval(timerRef.current);
       }
     };

     return (
       <div>
         <h1>Time: {count}s</h1>
         <button onClick={startTimer}>Start Timer</button>
         <button onClick={stopTimer}>Stop Timer</button>
       </div>
     );
   };

   export default Timer;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • timerRef.current is used to store the timer ID.
  • startTimer and stopTimer functions use timerRef.current to manage the timer.
  • Updating timerRef.current does not cause a re-render of the component.

Summary

  • useRef creates a mutable ref object with a .current property.
  • Use useRef to access DOM elements directly.
  • Use useRef to keep mutable values that do not cause re-renders.

That’s it! useRef is a powerful and versatile hook that’s useful in many scenarios.

💖 💪 🙅 🚩
singhpritpal04
Pritpal Singh

Posted on September 12, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related