Looking at the hooks docs and some blogs we understand that when using useRef() we have a mutable value stored.
Docs:
You might be familiar with refs primarily as a way to access the DOM. If you pass a ref object to React with , React will set its .current property to the corresponding DOM node whenever that node changes.
However, useRef() is useful for more than the ref attribute. It’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.
This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.
What advantages does this give us over just declaring and using a variable with let
?
Code ex:
import React, {useRef} from "react";
const MyFunctionalComponent = (props) => {
const refVariable = useRef('value');
//versus
let letVariable = 'value';
}
Follow up: The answers given were helpful, and combined with some testing gave me the understanding I needed. If anyone comes across this having trouble with the concept, the way I understand it now is:
The useRef hook is a very handy option for both interacting with DOM elements and storing mutating information in your app without triggering a re-render. However, it is suggested to only use the useRef when necessary and within a useEffect to avoid bugs.
If you want to update data and cause a UI update, useState is your Hook. If you need some kind of data container throughout the component's lifecycle without causing render cycles on mutating your variable, then useRef is your solution.
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.
The last sentence describes it clearly:
useRef will give you the same ref object on every render.
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 (Besides using the ref attribute for DOM node reference)
I'm changing my answer and referring people to Arman's below, since it's the more apt one. In essence, for functional components the entire function gets run every time it re-renders. Which means variables that are initialized with a simple let x = 5;
in the body of the function will get re-initialized every render, resetting them. That's the reason we need hooks like useRef
, it gives a reference to a value that persists between renders
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