useRef avoids repeated creation of initial values

1. The cache function of useRef, sharing data between multiple renderings - stop timer

Incorrect usage: every time setCount, refTimeId will be re-declared as null, resulting in timeId being null when the button is clicked, and closing the timer fails

import React, { useEffect, useState,useRef } from 'react'
const F:React.FC=()=> {
  const [count, setCount] = useState(0)
  const refTimeId = null
  console.log(refTimeId) //null
  useEffect(() => {
    refTimeId= setInterval(() => {
      setCount((count) => count + 1)
    }, 1000)
  }, [])
 
  const hClick = () => {
    console.log(refTimeId) // null
    clearInterval(refTimeId)
  }
 
  return (
    <div>
      count:{count}
      <button onClick={hClick}>点击停止定时器</button>
    </div>
  )
}

export default F

 Correct usage: useRef has a caching effect, define refTimeId with useRef, useRef will only be declared once, and its role is to provide a global variable that can be accessed in functional components without rendering the component

import React, { useEffect, useState,useRef } from 'react'
const F:React.FC=()=> {
  const [count, setCount] = useState(0)
  const refTimeId = useRef<NodeJS.Timer>()
  console.log(refTimeId.current)
  useEffect(() => {
    refTimeId.current= setInterval(() => {
      setCount((count) => count + 1)
    }, 1000)
    console.log(refTimeId.current) // 1
  }, [])
 
  const hClick = () => {
    console.log(refTimeId.current) // 1
    clearInterval(refTimeId.current)
  }
 
  return (
    <div>
      count:{count}
      <button onClick={hClick}>点击停止定时器</button>
    </div>
  )
}

export default F

2. Use useRef to get DOM elements

import React, { useRef } from 'react'
import reactDom from 'react-dom'
 
F:React.FC=()=>{
  const inputEl = useRef(null)
  const hClick = () => {
    inputEl.current.focus() // 这里的inputEl.current就是input元素,所以可以调用原生input的方法
  }
  return (
    <div>
      <input type="text" ref={inputEl} />
      <br />
      <button onClick={hClick}>表单获取焦点</button>
    </div>
  )
}
 
export F

The difference between useState and useRef

const [isVisible, setIsVisible] = useState(false), there is one thing worth noting here: calling the setIsVisible function will update the isVisible variable, but if you immediately print this state with consol.log, you will not get the latest value. We need to use the second parameter of useEffect to monitor the value we need to change to get the latest value after the change. In other words, after the component is re-rendered, we can see the latest value.

useState triggers re-rendering, useRef does not trigger

useState updates its value asynchronously, useRef updates synchronously

Variables are variables that determine the rendering of the view layer, please use useState, other uses useRef

Guess you like

Origin blog.csdn.net/u011200562/article/details/130246865