React.useRef reference
1 May 2022 (Updated 22 May 2022)
On this page
What is useRef useful for?
useRef
serves two main purposes:
- Store a reference to a DOM node or React element that will persist throughout a component’s life cycle – even between re-renders. In this sense, it’s similar to React.createRef. See this post for more about refs.
- Store a reference to a mutable value that will persist throughout the component lifecycle. In this sense,
useRef
can be used as an alternative instance variables in a class component. For example, you can useuseRef
to store a reference to the return value ofsetInterval
and then use this value to cancel the timer in the cleanup callback ofuseEffect
.
Example usage
function TextInputWithFocusButton() {
const inputEl = useRef(null)
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus()
}
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Other notes
- Mutating the
current
property doesn’t cause a re-render. If you must run code when a ref to a DOM node is attached or detached, consider using ref callbacks.
Sources
Tagged:
React
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment