hooks Series 4: useRefs

Posted by mashnote on Wed, 05 Jan 2022 10:48:26 +0100

Come and join us!

"The Rookies of Xiaoheshan" provide front-end developers with technology related information and a series of basic articles. For a better user experience, please move to our official website Xiaoheshan rookies( https://xhs-rookies.com/ )Study and get the latest articles in time.

Rookie, "Code tailor", if you are interested in our articles or want to make some suggestions, WeChat will pay attention to the official account of "Xiao Shan Shan's rookie" and contact us, you can also read our articles on WeChat. Every suggestion or approval is a great encouragement to us!

preface

The main purpose of this article is to understand the use of useRefs

useRefs

definition

useRef returns a mutable ref object whose The current property is initialized to the passed in parameter (initialValue). The returned ref object remains unchanged throughout the life cycle of the component.

const refContainer = useRef(initialValue)

As we all know, React has provided an API createRef, which is also used to create a ref. what is the meaning of this useRefs Hook? What's the difference between them?

Properties of useRef

An important feature of useref is that the ref object returned by useref is variable. As stated in the official website document, it is like a variable, like a "box" that can hold a variable value.

As we already know, the ref object returned by createRef will return a new reference every time it is rendered, while useRef will return the same reference. As stated in the definition, the returned ref object will remain unchanged throughout the life cycle of the component. This is why useRef can be used in its An important reason to keep a variable value in the current attribute.

It may be difficult to understand. Let's use an example to understand:

function about() {
  const [count, addCount] = useState(0)
  const refForUseRef = useRef()
  const refForCreateRef = createRef()

  if (!refForUseRef.current) {
    // Assignment if not present
    refForUseRef.current = count
  }
  if (!refForCreateRef.current) {
    refForCreateRef.current = count
  }

  return (
    <>
      <div>Now? count The value of is:{count}</div>
      <div>refForUseRef The value of is:{refForUseRef.current}</div>
      <div>refForCreateRef The value of is:{refForCreateRef.current}</div>
      <button onClick={() => addCount((val) => val + 1)}>click+1</button>
    </>
  )
}

Look at the effect. Even if the component is re rendered, the value of refForUseRef always exists, so it cannot be re assigned. That is why the reference to ref returned by useRef is the same and remains unchanged throughout the life cycle.

The role of useRef in Hook

We all know that the appearance of Hook enables us to achieve some features in Class components in function components. We need to pay attention to one thing. There is a concept in Class components called instance variables. Do Hook based function components have similar instance variables?

The answer is yes. useRef Hook can not only be used for DOM refs, but also plays an important role in accommodating a Class like instance attribute with any value, which is also the feature mentioned above.

Let's use an example to feel the charm of the function component using useRef.

Feel useRef with examples

Function components that do not use useRef

function about() {
  const [count, addCount] = useState(0)

  function handleAlertClick() {
    setTimeout(() => {
      alert('Bullet frame count value:' + count)
    }, 2000)
  }

  return (
    <div>
      <div>Now? count The value of is:{count}</div>
      <button onClick={() => addCount((val) => val + 1)}>click+1</button>
      <button onClick={() => handleAlertClick()}>Display bullet frame</button>
    </div>
  )
}

Observing the effect of this example, we can find that the count value in the pop-up box is the value when clicking the display pop-up box button, not the real-time state of count. Why?

In fact, when we update the state, React will re render the component, get an independent count state for each rendering, and re render a handleAlertClick function Each handlealerticlick has its own count. Therefore, each pop-up box displays the count value when clicking.

How to make the value in the pop-up box display the count value in real time?

useRef, which we have been discussing, is used at this time. Let's look at the example directly:

function about() {
  const [count, addCount] = useState(0)
  const refForUseRef = useRef(count)

  useEffect(() => {
    refForUseRef.current = count
  })

  function handleAlertClick() {
    setTimeout(() => {
      alert('Bullet frame count value:' + refForUseRef.current)
    }, 2000)
  }

  return (
    <div>
      <div>Now? count The value of is:{count}</div>
      <div>refForUseRef The value of is:{refForUseRef.current}</div>
      <button onClick={() => addCount((val) => val + 1)}>click+1</button>
      <button onClick={() => handleAlertClick()}>Display bullet frame</button>
    </div>
  )
}

Because useRef returns the same reference every time, it will also be modified in alert when it is modified in useEffect In this way, when you click, you can pop up a real-time count

In this example, count is similar to the instance variable in the Class component. useRef allows us to complete some functions of the Class component in the function component.

summary

Through this article, we learned that React Hook brings us a hook useRef. The ref object returned by it remains unchanged throughout the life cycle of the component. It allows us to save some instance attributes in function components like Class components, which brings us many possibilities for development. In addition to these novel functions, Don't forget the function of ref to get DOM attributes, because it can also be applied in useRef.

Next section Preview

In the next section, we will introduce useCallBack to you. Please look forward to it!

Topics: React