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.
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? Both refs and state variables provide a way to persist values between renders; however, only state variables trigger a re-render.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With