Regular variables get re-initialized every time the component re-renders. But
For example, if I initialize a regular variable like the one listed below, my
const random = Math.random()
let regVar = random
On the other hand, the same declaration with a
const random = Math.random()
const refVar = useRef(random)
Therefore,
A complete code snippet illustrates the difference between
import { useRef, useState } from "react"
export const FunctionalComponent = () =>{
const random = Math.random()
const refVar = useRef<number>(random)
let regVar = random
const [, setUpdate] = useState<boolean>()
return(<>
<div>Regvar = {regVar}</div>
<div>Refvar = {refVar.current}</div>
<div><button onClick={() => setUpdate((prev) => !prev)}>Re-render</button></div>
</>
)
}