What is useRef
useRef is developed with the development of react functional components. It is one of many official hooks of react. Calling useRef can return an object that does not change throughout the entire declaration cycle of this component. There are two common uses of this object:
- Used to bind dom elements, thereby implementing operations on dom elements
- Used to save values that do not want to change as the component is re-rendered, such as timers
Application in the project
I'm doingYour own websiteI encountered some scenarios, and the implementation effect was inconsistent with the expected ones, which made me feel overwhelmed for a while. Fortunately, they were all solved in the end. In order to be able to come back and take a look at it in the future and record some knowledge points during the learning process, I will record these two scenarios as follows.
1. Write your own anti-shake function
When writing the login and registration function, the information input by the user needs to be checked, including the front-end verification and the verification of communication with the back-end. If it is just the front-end verification, it is fine. If the information input by the user changes every time, the number of http requests will put pressure on the server, so I hope to prevent these behaviors from being shaken.
import { useEffect, useRef } from "react" export const useDebounce = (f:Function,delay:number)=>{ //Save the timer with useRef to ensure that the same timer is always the same when the component is updated, rather than recreating it const {current} = useRef<{timmer:any}>({timmer:null}) useEffect(()=>{ return ()=>{ //Clear the timer when component is destroyed clearTimeout() } },[]) return function(...args:any[]){ // If the timer exists, clear the timer if(){ clearTimeout() } //Reassign the timer and execute the callback function after the timing is over = setTimeout(() => { (useDebounce,args) }, delay); } }
Here I write the anti-shake function into a custom hook, which is also the first hook written. Two parameters need to be passed in when calling. The first parameter is a function that needs to be processed in anti-shake, and the second parameter is the delay time of anti-shake. The return value of the hook is a function that has been processed in anti-shake.
2. Solve the problem of not getting the latest state value in the callback function
When implementing the acquisition of comment list, I hope to only get a certain number of comments each time, and to obtain new comments when the user browses to the bottom of the page. I used it during the implementation process.intersectionObserver
API, and references some states in the component in its callback function.
When I directly bind the listening element in the useEffect side effect function, I found that the state value in the callback function has always maintained the value when the observer object was created. After querying relevant information, I learned that this may be due to the impact of the closure. The solution is to use useRef to create an object to save the observer object, and release the original observer object after the relevant state value changes, create a new observer object, and rebind the element to be listened to.
//Point to the element to be listened toconst bref = useRef(null) //Save the observer objectconst observer = useRef<any>() //Whenever comments change, an observer object will be recreated, and the callback function references the latest state value useEffect(() => { let c = new IntersectionObserver((entries) => { if (entries[0].intersectionRatio > 0) { if (page * pageNum <= count) { const fd = new FormData() ('articleId', ) ('page', page + 1) ('pageNum', pageNum) http({ url: '/comment/comments', options: { method: 'POST', body: fd } }).then(res => { if (count !== ) { setcount() } setpage(page + 1) setcomments([...comments, ...]) }) } } }) //Cancel old listening if () { () } //Save new observer object and create new listener = c () }, [comments])
Practice produces true knowledge, discover problems in projects, and find solutions to problems. The river continues to flow, accumulate, enrich your experience, and improve your abilities.
This is the article about the detailed explanation of the useRef application in react. For more relevant application content of useRef in react, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!