useRef vs. regular variable in React Js

Last updated : October 30, 2022

Regular variables get re-initialized every time the component re-renders. But useRef()'s returns the exact reference in each re-render. Therefore, the useRef()'s are an ideal candidate to preserve any values between component re-enders.

For example, if I initialize a regular variable like the one listed below, my regVar variable gets a new random number in each component re-render.

const random = Math.random()
let regVar = random

On the other hand, the same declaration with a useRef() yields a different result. In that case, my refVar is created and initialized when the component first mounts. It returns the same original reference when the component re-renders.

const random = Math.random()
const refVar = useRef(random)

Therefore, refVar.current remains the same between re-renders. The random number is generated when the component is first mounted in this case. That random number will stay the same between re-renders unless I re-assign it by refVar.current = random.

A complete code snippet illustrates the difference between useRef() and regular variables.

import { useRef, useState } from "react"

export const FunctionalComponent = () =>{
  const random = Math.random()
  const refVar = useRef<number>(random)
  let regVar = random
  const [, setUpdate] = useState<boolean>()

          <div>Regvar = {regVar}</div>
          <div>Refvar = {refVar.current}</div> 
          <div><button onClick={() => setUpdate((prev) => !prev)}>Re-render</button></div>
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.

Comments are disabled

No Comments