I am reading about React useState()
and useRef()
at "Hooks FAQ" and I got confused about some of the use cases that seem to have a solution with useRef and useState at the same time, and I'm not sure which way it the right way.
From the "Hooks FAQ" about useRef():
"The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class."
With useRef():
function Timer() { const intervalRef = useRef(); useEffect(() => { const id = setInterval(() => { // ... }); intervalRef.current = id; return () => { clearInterval(intervalRef.current); }; }); // ... }
With useState():
function Timer() { const [intervalId, setIntervalId] = useState(null); useEffect(() => { const id = setInterval(() => { // ... }); setIntervalId(id); return () => { clearInterval(intervalId); }; }); // ... }
Both examples will have the same result, but which one it better - and why?
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.
Use useRef if you need to manage focus, text selection, trigger imperative animations or integrating third-party libraries.
Both are the same, import {useState } from 'react' is less verbose and easy for readability and maintenance.
The useState hook is used for storing variables that are part of your application's state and will change as the user interacts with your website. The useEffect hook allows components to react to lifecycle events such as mounting to the DOM, re-rendering, and unmounting.
The main difference between both is :
useState
causes re-render, useRef
does not.
The common between them is, both useState
and useRef
can remember their data after re-renders. So if your variable is something that decides a view layer render, go with useState
. Else use useRef
I would suggest reading this article.
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