Come and join us!

“The Newbies of Little Wo Shan” provides front-end developers with technical information and a series of basic articles. For a better user experience, please go to xhs-rookies.com/ to learn the latest articles.

“Code Tailor “, if you are interested in our article, or would like to make some suggestions, please follow the official account of “Rookie of Xiaohe Mountain” on wechat and contact us. You can also view our article on wechat. Every suggestion or approval is a great encouragement to us!

preface

In this article, our main goal is to take a look at the use of useRefs.

useRefs

define

UseRef returns a mutable ref object whose.current property is initialized as the passed parameter (initialValue). The ref object returned remains constant throughout the life of the component.

const refContainer = useRef(initialValue)
Copy the code

React already provides an API called createRef, which is also used to create a ref. What’s the point of this useRefs Hook? What’s the difference between them?

The characteristics of useRef

An important feature of useRef is that the ref object returned by useRef is mutable. As stated in the documentation on the official website, it is like a variable, like a “box” that can hold a variable value.

We already know that createRef returns a ref object that returns a new reference every time it renders, whereas useRef returns the same reference and, as defined, the ref object that is returned remains the same throughout the life of the component. This is why useRef can store a mutable value in its.current property.

If this is hard to understand, let’s use an example:

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

  if(! refForUseRef.current) {// If it does not exist, the value is assigned
    refForUseRef.current = count
  }
  if(! refForCreateRef.current) { refForCreateRef.current = count }return (
    <>
      <div>Now count is: {count}</div>
      <div>RefForUseRef: {refForuseref.current}</div>
      <div>RefForCreateRef: {refForcreateref.current}</div>
      <button onClick={()= >AddCount ((val) => val +1)}> Click +1</button>
    </>)}Copy the code

If you look at the effect, even if the component is re-rendered, the refForUseRef value is always there, so it cannot be reassigned. That is why useRef returns the same reference to ref and remains the same throughout its lifetime.

UseRef’s role in hooks

As we all know, the emergence of Hook allows us to do some of the features of the Class component in the function component, we need to pay attention to one point, Class component has a concept called instance variable, so Hook based function component has similar instance variable?

The answer is yes, useRef Hook can be used not only for DOM refs, but also for holding class-like instance attributes with arbitrary values, which is a feature mentioned earlier.

Let’s use an example to get a feel for the power of using useRef’s functional components.

Experience useRef with examples

Function components that do not use useRef

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

  function handleAlertClick() {
    setTimeout(() = > {
      alert('Popbox count value :' + count)
    }, 2000)}return (
    <div>
      <div>Now count is: {count}</div>
      <button onClick={()= >AddCount ((val) => val +1)}> Click +1</button>
      <button onClick={()= >HandleAlertClick ()}> Display popbox</button>
    </div>)}Copy the code

Observing the effect of this example, we can find that the value of count in the popbox is the value when the popbox button is clicked, not the real-time state of count. Why is this?

In fact, when we update the state React will re-render the component, getting a separate count state for each render and re-rendering the handleAlertClick function. Each handleAlertClick has its own count inside it. So every time it pops up, it shows you the count value when you click on it.

How do I make the value in the popup display the count value in real time?

This is where useRef, which we’ve been talking about, comes in:

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

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

  function handleAlertClick() {
    setTimeout(() = > {
      alert('Popbox count value :' + refForUseRef.current)
    }, 2000)}return (
    <div>
      <div>Now count is: {count}</div>
      <div>RefForUseRef: {refForuseref.current}</div>
      <button onClick={()= >AddCount ((val) => val +1)}> Click +1</button>
      <button onClick={()= >HandleAlertClick ()}> Display popbox</button>
    </div>)}Copy the code

Because useRef returns the same reference every time, changes made in useEffect are also made in alert. That way, when you click, you can pop up a live count.

In this case, count is like an instance variable in the Class component, and useRef lets us do some of the Class component functions in the function component.

conclusion

React Hook provides a Hook called useRef, which returns a ref object that remains unchanged throughout the life cycle of a component. This Hook allows us to store instance properties in function components as well as Class components, opening up many possibilities for development. In addition to these novelty features, don’t forget the ability for REF to start retrieving DOM attributes, because useRef also works.

Next day forecast

In the next section, we will introduce the useCallBack, so stay tuned!