Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useRef vs. Regular Variable

I am confused about the differences between the useRef hook and a plain variable inside the component.

Am I right that every component renders, the plain variable also re-renders and persists its value, but the useRef just persists the value and does not re-render?

If that so, what would you recommend between the two?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is a sandbox for simulation!

Assuming

let a = 0;
const ref = useRef(0);
const [state,setState] = useState(0);

Now let’s say you use 2 buttons with these click functions

const firstClick = () => {
 a = 2;
 ref.current = 2;
}

const secondClick = () => {
 setState(2);
}

The first click will modify both the ref and the variable.

The Second click will cause a re-render because of a state change.

However if you are printing both ref and variable in a div or text then you will see only ref still persists its value, because React functions form a closure on their variables.

Wherever you need to manipulate Dom or store state without re-rendering on change, ref is your go-to. If you are making logical calculations then go for variables

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading