Understanding React useRef Hook

The useRef hook is a powerful hook in React that provides a way to create a mutable reference that persists across renders. It is commonly used to access or store references to DOM elements and other values without triggering re-renders. In this blog post, we'll explore the useRef hook in detail with different examples.

Understanding React useRef Hook


Basic Usage

The basic syntax of useRef is:

const ref = useRef(initialValue);

Where ref is the mutable ref object that can hold a value, and initialValue is the initial value of the ref.

Example 1: Accessing DOM Elements

One common use case of useRef is to access DOM elements:

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

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

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return (
    <div>
      <input ref={inputRef} type="text" />
    </div>
  );
}

Example 2: Storing Previous Values

Another use case is storing previous values across renders:

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

function Counter() {
  const countRef = useRef(0);
  const prevCountRef = useRef();

  useEffect(() => {
    prevCountRef.current = countRef.current;
  }, [countRef.current]);

  const increment = () => {
    countRef.current += 1;
    console.log('Current count:', countRef.current);
    console.log('Previous count:', prevCountRef.current);
  };

  return (
    <div>
      <button onClick={increment}>Increment</button>
    </div>
  );
} 

Example 3: Preserving Values

You can also use useRef to preserve values across renders without triggering re-renders:

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

function Timer() {
  const intervalRef = useRef();
  const [count, setCount] = useState(0);

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setCount(count => count + 1);
    }, 1000);

    return () => {
      clearInterval(intervalRef.current);
    };
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
    </div>
  );
}

Conclusion

The useRef hook is a versatile tool for managing references in React functional components. Whether you're accessing DOM elements, storing previous values, or preserving values across renders, useRef provides a clean and efficient way to work with mutable values without triggering re-renders.

Experiment with different use cases and explore the flexibility of useRef to enhance the functionality and interactivity of your React applications!

Previous Post Next Post

Contact Form