Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between useRef and normal variable

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.

like image 610
Hypothesis Avatar asked Aug 16 '19 19:08

Hypothesis


People also ask

When should we use useRef?

The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.

What is the difference between refs and state variables?

What is the difference between refs and state variables? Both refs and state variables provide a way to persist values between renders; however, only state variables trigger a re-render.

How does useRef store value?

Storing element references with useRef To do this, create the ref, and then pass it into the element: const Component = () => { const ref = useRef(null); return <div ref={ref}> Hello world </div>; }; With this reference, you can do lots of useful things like: Grabbing an element's height and width.

Is useRef same as createRef?

useRef: The useRef is a hook that uses the same ref throughout. It saves its value between re-renders in a functional component and doesn't create a new instance of the ref for every re-render. It persists the existing ref between re-renders. createRef: The createRef is a function that creates a new ref every time.


2 Answers

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.

like image 86
aviya.developer Avatar answered Oct 06 '22 14:10

aviya.developer


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.

like image 30
Federkun Avatar answered Oct 06 '22 13:10

Federkun