The useRef
hook in React provides a way to persist values across renders without causing re-renders when the value changes. It returns a mutable ref object whose .current
property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
Here's a basic example of how to use useRef
:
import React, { useRef } from 'react'; function TextInputWithFocusButton() { const inputRef = useRef(null); const handleClick = () => { // Focus the input element on button click inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={handleClick}>Focus Input</button> </div> ); } export default TextInputWithFocusButton;
In this example:
useRef()
.ref
attribute of the input element.handleClick
function is called, which calls the focus()
method on the input element, setting the focus to it.useRef
to directly access the DOM nodes or other imperative APIs provided by third-party libraries.current
: While you can directly mutate the .current
property of a ref, it's generally not recommended in React code. Instead, use the provided useRef
methods (createRef
or useRef
) to interact with refs.useRef
is commonly used to access uncontrolled components, such as input fields, without needing to make them controlled components.