Reputation: 11054
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:
Upvotes: 20
Views: 9782
Reputation: 9063
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
Upvotes: 15
Reputation: 945
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)
Upvotes: 21