React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef…

React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef Hook

Photo by Lautaro Andreani on Unsplash

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.

Learn more

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


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

React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef Hook

Photo by Lautaro Andreani on Unsplash

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.

Learn more

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


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef…." Atanas Dimitrov | Sciencx - Wednesday February 22, 2023, https://www.scien.cx/2023/02/22/react-newbies-guide-efficiently-managing-dom-elements-and-persistent-variables-with-the-useref/
HARVARD
Atanas Dimitrov | Sciencx Wednesday February 22, 2023 » React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef…., viewed ,<https://www.scien.cx/2023/02/22/react-newbies-guide-efficiently-managing-dom-elements-and-persistent-variables-with-the-useref/>
VANCOUVER
Atanas Dimitrov | Sciencx - » React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef…. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/02/22/react-newbies-guide-efficiently-managing-dom-elements-and-persistent-variables-with-the-useref/
CHICAGO
" » React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef…." Atanas Dimitrov | Sciencx - Accessed . https://www.scien.cx/2023/02/22/react-newbies-guide-efficiently-managing-dom-elements-and-persistent-variables-with-the-useref/
IEEE
" » React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef…." Atanas Dimitrov | Sciencx [Online]. Available: https://www.scien.cx/2023/02/22/react-newbies-guide-efficiently-managing-dom-elements-and-persistent-variables-with-the-useref/. [Accessed: ]
rf:citation
» React Newbies Guide: Efficiently Managing DOM Elements and Persistent Variables with the useRef… | Atanas Dimitrov | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.