const refContainer = useRef(initialValue);
useRef
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.
Example: get the value of the input text
import React, {useRef} from 'react';
export default function App() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
console.log(inputEl.current.value);
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
You might be familiar with refs primarily as a way to access the DOM. If you pass a ref object to React with <div ref={myRef} />
, React will set its .current
property to the corresponding DOM node whenever that node changes.