useRef in ReactJS

dinesh priyantha
2 min read4 days ago

--

useRef is a hook in React that provides a way to create a reference to a DOM element or to persist a mutable value across renders without causing a re-render. This hook is particularly useful for accessing DOM elements directly, storing mutable values that do not trigger re-renders, and managing timers or other instances that need to persist between renders.

Here are detailed examples of how to use useRef in various scenarios:

1. Accessing DOM Elements

Example: Focusing an Input Element

import React, { useRef } from 'react';

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

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

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

export default FocusInput;

In this example:

  • useRef creates a ref object with a current property initialized to null.
  • The ref object is passed to the input element via the ref attribute.
  • The focusInput function sets the focus on the input element by accessing inputRef.current.

2. Persisting Mutable Values

Example: Tracking Previous Value

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

const PreviousValue = () => {
const [count, setCount] = useState(0);
const prevCountRef = useRef();

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

return (
<div>
<p>Current count: {count}</p>
<p>Previous count: {prevCountRef.current}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};

export default PreviousValue;

In this example:

  • prevCountRef is used to store the previous value of count.
  • The useEffect hook updates prevCountRef.current with the current count after each render.

3. Avoiding Re-renders

Using useRef to store a value that persists across renders without causing the component to re-render when the value changes.

Example: Storing Interval ID

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

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

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

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

return (
<div>
<p>Count: {count}</p>
<button onClick={() => clearInterval(intervalRef.current)}>Stop Timer</button>
</div>
);
};

export default Timer;

In this example:

  • intervalRef is used to store the interval ID.
  • The interval is cleared when the component unmounts or when the “Stop Timer” button is clicked, preventing potential memory leaks.

Summary

  • Accessing DOM elements: Use useRef to create a reference to a DOM element and manipulate it directly.
  • Persisting mutable values: Use useRef to store values that need to persist across renders without causing re-renders.
  • Avoiding re-renders: Use useRef to store values that should not trigger re-renders when updated.

useRef is a powerful tool for handling direct DOM manipulations and storing mutable values efficiently in functional components.

--

--