React useRef() Usage

Valeria Fischer
2 min readNov 3, 2023

--

useRef is a Hook in React that provides a way to create and maintain a mutable reference to a DOM element or any other value that you want to persist between renders without causing the component to re-render when the reference changes. It's particularly useful for accessing and interacting with DOM elements, managing focus, integrating with third-party libraries, or storing values that don't need to trigger re-renders

We import useRef from React.

Inside the ExampleComponent function, we create a myRef variable using useRef(). This creates a mutable object that has a .current property, which can be used to store a reference to a DOM element.

We use the useEffect hook to access the myRef after the component has rendered. This ensures that the DOM element is available when we try to access it.

We render a button that, when clicked, focuses the input element. We do this by accessing the input element using myRef.current and calling the focus() method on it.

We also set the color of the input element to blue using myRef.current.style.color.

Using useRef, you can access and interact with DOM elements without directly manipulating the DOM, which is a common pattern in React. It's essential for managing imperatively controlled components, like input fields, modals, and more, where you need to control them through JavaScript rather than React state.

--

--

Valeria Fischer
Valeria Fischer

Written by Valeria Fischer

FullStack Developer / Coder Girl

No responses yet