Skip to content

Latest commit

 

History

History
33 lines (21 loc) · 2.2 KB

useRef.md

File metadata and controls

33 lines (21 loc) · 2.2 KB

useRef

useRef is stable across re-renders

  • React stores the ref to remain immutable over the course of the lifetime of the component (especially if the contents (i.e. ref.current value) gets mutated). Thus, useRef value remains the same across re-renders.
  • When to use it? - You need a sort of data storage which doesn't influnce re-renders and which is tied to the component, so it's not a global variable.
  • CodeSandBox: ref vs. state vs. local variable (JS) shows the difference to an object value in useState and local variables.

useRef is bound to a component instance

useRef reflects "current" value irrespective of re-renders

  • Using ref displays current value because the ref object is guaranteed to remain stable for the lifetime of the component.

  • CodeSandBox: async state with timeout and ref

  • Task: Change the value displayed in the alert to the ref value.

  • You should observe that the state value "closes over" the timeout. It's frozen. But the updated ref value is accessible because it got updated

  • React Native Question: Why is React Native Animated value stored in ref?

  • Answer: Because we want Animation value to change independent of rendering of component in which animated value gets defined.

  • You don’t have any guarantees that reading the refs value countRef.current would give you the same value in any particular callback (as opposed to state and props values). By definition, you can mutate it any time.

[Extra] Other definition of ref

In a tweet Dan Abramov gave an interesting definition of a ref:

useRef() is basically useState({ current: initialValue })[0]

  • Discussion: Why does this make sense?

  • TODO: Add CodeSandBox with this as an example.