The difference between createRef and useRef in react

foreword

A previous article introduced the use of ref in react, which introduced the use of useRef in detail, click the link to view:
Analysis of the use of ref in react . This article introduces you to a new thing - useRef, let's see how they are different

useRef

In order to facilitate comparison, the following example uses useRef and useRef:
1. Use useRef and useRef to create two input boxes respectively, and print the corresponding values
​​2. Print the information of these two input boxes in useEffect

import React, {
    
     createRef, useRef, useEffect } from 'react'
export default function App() {
    
    
    const inputRef = createRef(1)
    console.log(inputRef)

    const useInputRef = useRef(2)
    console.log(useInputRef)

    useEffect(() => {
    
    
        console.log(inputRef)
        console.log(useInputRef)
    })
    return (
        <div>
            value: {
    
    inputRef.current}
            <input type="text" ref={
    
    inputRef} />
            <button onClick={
    
    e => {
    
    inputRef.current.focus();inputRef.current.value=4}}>获取焦点</button>
            <br/>
            value: {
    
    useInputRef.current}
            <input type="text" ref={
    
    useInputRef} />
            <button onClick={
    
    e => {
    
    useInputRef.current.focus();inputRef.current.value=4}}>获取焦点</button>
        </div>
    )
}

Look at the result:
insert image description here
as you can see, we give createRef(1), useRef(2), but why does inputRef print as null and useInputRef prints as 2?
This is because createRef will create a new ref object every time it is re-rendered. When it is used in the class component, there will be a corresponding life cycle to render it and call the render method, so in the functional component it does not Without implementing something like useRef, you just get a null value every time you re-render.

So in use, try to use createRef in the class component and useRef in the function component. After useRef renders an object for the first time, when it is re-rendered, if it finds that the object has already been created, it will not be created again, and the performance will be better

Summarize

1.createRef will create a new ref object every time it is re-rendered. 2. useRef will create
an object after the first rendering. The performance will be better
3. Try to use createRef in class components and useRef in hooks

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/123603541