admin管理员组

文章数量:1404357

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.

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.

Share Improve this question edited Mar 27, 2022 at 22:49 Hypothesis asked Aug 16, 2019 at 19:57 HypothesisHypothesis 1,3894 gold badges24 silver badges53 bronze badges 2
  • I'm not entirely certain due to an inexperience with hooks, but my understanding is that useRef is scoped to the instance of the ponent such that if you render multiple of the same ponent each one has a different ref object. – zzzzBov Commented Aug 16, 2019 at 20:20
  • Check out this question. I think you will find your answer. stackoverflow./questions/57444154/… – tsm Commented Jan 30, 2021 at 17:37
Add a ment  | 

3 Answers 3

Reset to default 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 ponent gets exported. So when you use ref, you have the access to a persistent variable without going outside of the ponent scope, so you can still use it when exporting.

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

React.useRef(0) is part of the ponent 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.

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 ponent, and used it inside the ponent, if you want to change it, it will break the functional programming rules (pure functions) and would have unintended side effects

本文标签: javascriptDifference between useRef and normal variableStack Overflow