useRefReturns a mutable ref object of.currentProperty is initialized as the passed parameter (initialValue). The ref object returned persists throughout the life of the component.

  • To obtain and manipulate the DOM imperatively:

    function TextInputWithFocusButton() {
      // Create and get Dom elements with useRef
      const inputEl = useRef(null);
        
      const onButtonClick = () = > {
        // 'current' points to the text input element mounted to the DOM
        inputEl.current.focus();
      };
      return (
        <>
          <input ref={inputEl} type="text" />
          <button onClick={onButtonClick}>Focus the input</button>
        </>
      );
    }
    Copy the code
  • UseRef creates a variable that is not affected by component refresh

    import React, { useRef, useState, useEffect } from "react";
    ​
    function UseRef() {
      const [x,setX] = useState(0)
    ​
      // As soon as the function component is updated, a is reset to 0, so the function component needs to use useRef to store variables
      let a = 0
      //useRef can generate a variable to store data in a function component
      let currentVal = useRef(0)
    ​
      // Create and get Dom elements with useRef
      const inputElement = useRef(null);
    ​
      useEffect(() = >{
        console.log(`useEffect --- x:${x} --- currentVal:${currentVal.current} --- a:${a}`);
      },[x])
      
      return (
        <>
          <p>{x} ----</p>
          <button onClick={()= >{ setX(v=>v+1) ;  currentVal.current+=2 ; a+=2 }}>+1</button>
        </>
      );
    }
    Copy the code

    Click +1 and the page will print:

    • useEffect --- x:1 --- currentVal:2 --- a:0
    • useEffect --- x:2 --- currentVal:4 --- a:0
    • useEffect --- x:3 --- currentVal:6 --- a:0

    Since a is a normal variable, any button click will cause the function component to refresh, generating a new A that will always be 0. So if you want to create a variable within a function component that is not affected by a component refresh, you must use useRef generation

The Denver nuggets:Juejin. Cn/user / 303430…All original good articles

CSDN:Blog.csdn.net/qq_42753705…All original good articles

Jane’s book:www.jianshu.com/u/460b662a0…All original good articles

Segmentfault think no:Segmentfault.com/u/jasonma19…All original good articles

Blog garden :www.cnblogs.com/Jason1995/All original good articles