React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef Hook
The useRef React hook is a powerful tool that allows you to create and manipulate references to DOM elements and other values within your components. This can be extremely useful when working with forms, animations, and other complex user interactions. In this article, we’ll explore the two most common usages of useRef and show you examples of how it can be used in your projects.
Store a Reference to a DOM Element
The first common usage of useRef is to store a reference to a DOM element. This can be useful when you need to interact with the DOM directly, such as focusing an input field or measuring the size of an element. Here’s an example of how you might use useRef to store a reference to a button element:
import { useRef } from 'react';
const Example = () => {
const buttonRef = useRef(null);
const handleClick = () => {
buttonRef.current.innerHTML = 'Clicked!';
}
return (
<button ref={buttonRef} onClick={handleClick}>Click me</button>
);
}
In this example, the useRef hook is being used to create a buttonRef variable that will store a reference to the button element. The ref attribute is then used to attach the reference to the button element. Then we use the current property of the ref object to change the innerHTML of the button element.
Store a Variable that will not get Re-rendered
The second common usage of useRef is to store a variable that will not get re-rendered with the component. This can be useful when you need to store some variable that doesn’t change but you don’t want to store it in the state. For example, you can use useRef to store a setInterval function:
import { useState, useRef } from 'react';
const Example = () => {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef(null);
useEffect(() => {
intervalRef.current = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(intervalRef.current);
}, []);
return (
<>
<h1>{seconds}</h1>
<button onClick={() => clearInterval(intervalRef.current)}>
Stop timer
</button>
</>
);
}
In this example, we are using useRef to store the setInterval function and then use it in the cleanup function of useEffect to stop the interval when the component unmounts. This way, the setInterval function does not get re-created and re-assigned on every render, which could cause unnecessary performance issues.
In conclusion, useRef is a versatile hook that can be used in a variety of ways to create and manipulate references to DOM elements and other values in your React components. Whether you’re working with forms, animations, or other complex user interactions, useRef is a powerful tool that can help you write more efficient and maintainable code.
Comments ()