This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

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

(4) The principle of useRef

When to use refs

Typically, when your component needs to “jump out” of React and communicate with an external API, you’ll use the REF – usually a browser API that doesn’t affect the look and feel of the component. Here are some rare cases:

  • Store the timeout ID
  • Storing and manipulating DOM elements is described in a later article
  • Store other objects that do not need to evaluate JSX

Select Refs if the component needs to store some values without affecting the Render logic.

Best practices for REF

Following these principles will make your components more predictable:

  • Think of refs as escape pods. Refs is useful when you use external systems or browser apis. If most of your application logic and data flow depends on REFS, you may need to rethink your approach.
  • Do not read or write ref.current during render.If you need some information during rendering, use state instead. Because React doesn’t know when the ref.current changes, reading it at render time makes the behavior of the component unpredictable. (The only exception is likeif (! ref.current) ref.current = new Thing()This code sets only one ref during the first render.

The React State restriction does not apply to Refs. For example, state is like a snapshot of each render and does not synchronize updates. But when you change the current value of ref, it immediately changes:

ref.current = 5;
console.log(ref.current); / / 5
Copy the code

This is because ref itself is a normal JavaScript object, so it behaves like this.

You also don’t have to worry about avoiding mutations when you use ref. React doesn’t care what you do with the ref or its contents as long as the object you’re mutating isn’t used for rendering.