This content originally appeared on Bits and Pieces - Medium and was authored by Atanas Dimitrov
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.
Before you’re gone
Please, consider showing some ❤️ and give this article a 👏🏻! Your support means a lot to me as a new writer.
Thank you! 🙇🏻
Build apps with reusable components like Lego
Bit’s open-source tool help 250,000+ devs to build apps with components.
Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.
Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:
→ Micro-Frontends
→ Design System
→ Code-Sharing and reuse
→ Monorepo
Learn more
- How We Build Micro Frontends
- How we Build a Component Design System
- Bit - Component driven development
- 5 Ways to Build a React Monorepo
- How to Create a Composable React App with Bit
React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef… was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Atanas Dimitrov
Atanas Dimitrov | Sciencx (2023-02-22T20:44:36+00:00) React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef…. Retrieved from https://www.scien.cx/2023/02/22/react-newbies-guide-efficiently-managing-dom-elements-and-persistent-variables-with-the-useref/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.