Application scenarios

Gets an instance of a component, for example when the parent component needs to call methods of the child component. Get the DOM object, which is used to bind some DOM, listen to the component’s events as global variables in the function component, save data across the render cycle, that is, the component remains unchanged after many times of rendering. State cannot store data across the render cycle, because once state changes it, it will cause the re-rendering of the component. UseRef does not re-cause rendering.

features

  • UseRef returns a mutable ref object whose.currentN track is initialized as an initalValue. The ref object returned remains unchanged for the lifetime of the component.
  • A change in the value of curent does not cause the component to be re-rendered; it is equivalent to a component’s global variable.
  • Ref and render maintain a reference relationship, that is, the address of the reference, it must get the latest state.

grammar

const refContainer = useRef(initialValue);

Usage examples

(1) DOM acquisition

const inputEl = useRef(null); Const onButtonClick = () => {// 'current' points to the text input element inputel.current.focus () mounted to the DOM; }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }Copy the code

(2) The parent component calls the child component method

UseImperativeHandle ChildComp = (props,ref) => {useImperativeHandle = ref (props,ref) => UseImperativeHandle (ref, () => ({// changeVal is the method exposed to the parent component changeVal: (newVal) => {}})); Return (<div>{val}</div>)} ChildComp = forwardRef(ChildComp); const FComp = () => { const childRef = useRef(); Const updateChildState = () = > {/ / changeVal is the way children exposed to the parent component childRef. Current. ChangeVal (99); } return (<> <ChildComp ref={childRef} /> <button onClick={updateChildState}> </button> </>)}Copy the code

(3) Component global variables

function App() { const [count, setCount] = useState(0); Const timer = useRef(); const timer = useRef(); UseEffect (() => {timer.current = setInterval(() => {setCount(count => count + 1); }, 1000); } []); UseEffect (() => {if (count > 5) {clearInterval(timer.current); }}); return <h1>count: {count}</h1>; }Copy the code