UseRef is used in Hooks to retrieve Dom elements and can also be used to hold variables. UseRef returns a ref object whose.current is initialized. The ref object returned remains constant throughout the life of the component.
-
Gets the Dom element usage
// Comp1,js import React,{ useRef } from 'react'; function Comp1() { / / create the ref const inputEl = useRef(); function getValue(){ // Get input value inputel. current, which is the Dom tag console.log(inputEl.current.value); } return ( <div>* /} {/ * assignment<input ref={inputEl} type="text" /> <button onClick={getValue}>Click to get the value</button> </div>)}export default Comp1; // index.js import React from 'react'; import ReactDOM from 'react-dom'; import Comp1 from './Comp1'; ReactDOM.render(<Comp1 />.document.getElementById('root')); Copy the code
-
Save variable usage
//Comp2.js import React,{ useState,useEffect,useRef } from 'react'; function Comp2() { const [text,setText] = useState('text'); const textRef = useRef(); useEffect(() = >{ // This function is triggered when data is updated // Each change is saved once textRef.current = text; }) return ( <div> <input type="text" value={text} onChange={e= >{setText(e.target.value)}} /> {/* get variable */}<h2>{textRef.current}</h2> </div>)}export default Comp2; // index.js import React from 'react'; import ReactDOM from 'react-dom'; import Comp2 from './Comp2'; ReactDOM.render(<Comp2 />.document.getElementById('root')); Copy the code
In essence, useRef is like a box, and its.current can be used to store any mutable content