Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

Translate: beta.reactjs.org/learn/refer…

When you want the component to “remember” some information, but you don’t want that information to trigger a rerender, you can use the ref, which is like a secret “pocket” for storing information in the component.

series

1. Use useRef

(2) The useRef example

(3) compare ref and state

How does useRef work internally?

Although both useState and useRef are provided by React, in principle useRef can be implemented on top of useState. As you can imagine inside React, useRef is implemented like this:

/ / the React within
function useRef(initialValue) {
  const [ref, unused] = useState({ current: initialValue });
  return ref;
}
Copy the code

For the first rendering, useRef returns {current: initialValue}. The object will be stored by React, so the next render will return the same object. Note that the unused state setting function is not used in this example. It is not needed because useRef always only needs to return the same object!

React provides a built-in version of “useRef” because it is common in practice. But you can think of it as a normal state variable with no state setting function. If you’re familiar with object-oriented programming, refs might remind you of instance fields, but it’s written somethingRef.current, not this.something