DEV Community

Md Yusuf
Md Yusuf

Posted on

useRef Hook Explained

The useRef hook in React is a powerful feature that allows you to create a mutable reference to a DOM element or any other value that persists for the entire lifecycle of a component. Here’s a detailed explanation of how it works, along with its use cases:

What is useRef?

  • Persistent Storage: useRef provides a way to hold a mutable reference that does not trigger a re-render when updated. This is different from state, where updating a state variable will cause the component to re-render.

  • Returns a Mutable Object: When you call useRef(initialValue), it returns a mutable object with a current property that you can modify. The initial value you pass to useRef is set to current, but you can change current at any time.

Basic Syntax

const myRef = useRef(initialValue);
Enter fullscreen mode Exit fullscreen mode

Example of useRef

Here’s a simple example where useRef is used to access a DOM element:

import React, { useRef } from 'react';

function FocusInput() {
  const inputRef = useRef(null);

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

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

export default FocusInput;
Enter fullscreen mode Exit fullscreen mode

Explanation of the Example

  1. Creating a Ref: const inputRef = useRef(null); creates a reference to hold a reference to the input element.

  2. Assigning the Ref: The ref attribute of the input element is assigned to inputRef. This allows React to attach the input DOM element to the current property of inputRef.

  3. Accessing the Ref: When the button is clicked, the focusInput function accesses the input element through inputRef.current and calls focus() on it.

Use Cases

  1. Accessing DOM Elements: As shown in the example, useRef is commonly used to access and interact with DOM elements directly.

  2. Storing Mutable Values: You can use useRef to store any mutable value that doesn’t require re-rendering when changed, such as a timer ID or a previous value.

   const timerRef = useRef();

   const startTimer = () => {
     timerRef.current = setTimeout(() => {
       // some action
     }, 1000);
   };

   const stopTimer = () => {
     clearTimeout(timerRef.current);
   };
Enter fullscreen mode Exit fullscreen mode
  1. Persisting Values Across Renders: Unlike state, a value held in useRef does not reset on re-renders. This can be useful for keeping track of values that are used in callbacks or effects.

  2. Integrating with Third-party Libraries: When using third-party libraries that manipulate the DOM directly, useRef can provide a way to keep a reference to those DOM nodes.

Comparison with useState

  • Re-renders: Updating a state variable with useState will trigger a re-render of the component, while updating a useRef will not.

  • Storage: Use useRef for values that do not affect the rendering of the component, whereas useState should be used for values that do.

Key Points to Remember

  • useRef can hold any value, not just DOM elements.
  • The current property can be updated freely without causing a re-render.
  • Ideal for accessing DOM nodes or storing mutable values that don’t need to trigger a render.

By understanding these concepts, you can effectively utilize the useRef hook in your React applications! If you have any specific use cases or questions about useRef, feel free to ask!

Top comments (0)