8

I wonder about the difference between these 2 codes

1 :

import React from "react";
import ReactDOM from "react-dom";


function App() {
  const myref = React.useRef(0);

2:

import React from "react";
import ReactDOM from "react-dom";

let myref = 0;
function App() {
 

Now at any point I can mutate both values and both are kept in the dom. What is their difference in usage.

Hypothesis
  • 1,208
  • 3
  • 17
  • 43
  • I'm not entirely certain due to an inexperience with hooks, but my understanding is that `useRef` is scoped to the instance of the component such that if you render multiple of the same component each one has a different ref object. – zzzzBov Aug 16 '19 at 20:20
  • Check out this question. I think you will find your answer. https://stackoverflow.com/questions/57444154/why-need-useref-to-contain-mutable-variable-but-not-define-variable-outside-the – tsm Jan 30 '21 at 17:37

3 Answers3

4

I think that the difference is about the Component packaging and exporting. Let's say you import App from the file, this doesn't mean the whole file is exported, this is a module, only the exported App component gets exported. So when you use ref, you have the access to a persistent variable without going outside of the component scope, so you can still use it when exporting.

Also how would you differentiate between multiple instances of the App component that might need a different value with the same variable? useRef() automatically distinguishes those.

aviya.developer
  • 3,343
  • 2
  • 15
  • 41
3

React.useRef(0) is part of the component life-cycle. If you render two different App in your application, those two ref won't collide. They will if you refer to the same shared and mutable variable, like in your second example. You will have a situation where one instance of App will have unintended side effects to the second instance of App.

Federkun
  • 36,084
  • 8
  • 78
  • 90
-1

In general, If you declare a simple JavaScript variable yourself, it will be updated on each render. Refs are used when you need to persist some value during re-renders, actually it will give you the same ref object on every render.

But in this case, you've moved the variable outside the component, and used it inside the component, if you want to change it, it will break the functional programming rules (pure functions) and would have unintended side effects

Hamid Shoja
  • 3,838
  • 4
  • 30
  • 45
  • React components with hooks are not [pure functions](https://en.wikipedia.org/wiki/Pure_function) by definition. Whether you `useRef` or use outside state they aren't pure – Zachiah Jul 05 '23 at 13:33