The useRef Hook lets you store a mutable value that persists across component renders. It is commonly used to access DOM elements or keep values without causing re-renders.
Returns an object with a .current property to hold any value
Updating .current does not trigger a re-render
Useful for DOM access, timers, and storing previous values
Syntax
const refContainer = useRef(initialValue);
Implementing the useRef hook
The useRef hook is used to access DOM elements and persist values across renders without triggering re-renders.
- Accessing the DOM using the useRef hook
A ref created with useRef is attached to the textarea, allowing the click handler to access the DOM element and programmatically set focus.
import React, { Fragment, useRef } from 'react';
function App() {
const focusPoint = useRef(null);
const onClickHandler = () => {
focusPoint.current.value =
"The quick brown fox jumps over the lazy dog";
focusPoint.current.focus();
};
return (
<Fragment>
<div>
<button onClick={onClickHandler}>
ACTION
</button>
</div>
<label>
Click on the action button to
focus and populate the text.
</label><br />
<textarea ref={focusPoint} />
</Fragment>
);
};
export default App;
useRef creates a reference to focusPoint, which allows direct manipulation of the DOM element.
Clicking the "ACTION" button triggers onClickHandler, which sets text in the textarea and focuses it.
(<>...</>) is used to group multiple elements without adding extra wrappers in the DOM.

Top comments (0)