gvlax
gvlax

Reputation: 788

Difference between useRef() and { }

I am reading about useRef() and playing with simple examples.

What surprises me is that whenever I replace

const MyComponent = ({value}) => {
  const myRef = useRef();
  [...]

with

const MyComponent = ({value}) => {
  const myRef = {};
  [...]

a component works in the same way. Do you know any example that would show the real advantage of the hook?

Upvotes: 0

Views: 39

Answers (1)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

Well, try

  const myRef = {};
  //..
  // at some point e.g. in click handler do:
  myRef.a = 123;

Now trigger a rerender of the component and log value of myRef, you will see the change you made above will be lost on the next render. On each render a new myRef is created. The value returned by useRef on the other hand is persisted for the full lifetime of the component.

Upvotes: 1

Related Questions