3 min read
Variables vs State vs Refs

What is the main difference between these three?

To begin with, variables aren’t preserved between re-renders and don’t trigger a re-render if their value changed.

Refs on the other hand are preserved (ref.current) but don’t trigger a re-render if their value is changed.

State is preserved and triggers a re-render if changed.

So now we know these stuff, when should we use them?

When to use which?

Variables:

You use them when you need to calculate or format a value that is derived directly from props or state and is only relevant for the current render cycle.

For example, if you need to format a date or calculate a derived value based on props, you can use a variable.

function MyComponent({ date }) { 
  const formattedDate = new Date(date).toLocaleDateString();

  return <div>{formattedDate}</div>;
}

You may say “I can pass it formatted already”, yes but you may need to have different formats (for whatever reason) for the same date that a specific component wants to render. Variables may be useful here.

Refs:

You can use refs to store a value that persists across re-renders and change it without causing the component to re-render, or to access a DOM element directly. But I’ll discuss that in another post maybe.

It is mostly used with values you don’t want to display, like time Interval ID (setInterval) and clearing them out.

This is from React Docs, in this code, changing intervalRef.current value doesn’t lead to a re-render.

import { useState, useRef } from 'react';

export default function Stopwatch() {
  const [startTime, setStartTime] = useState(null);
  const [now, setNow] = useState(null);
  const intervalRef = useRef(null);

  function handleStart() {
    setStartTime(Date.now());
    setNow(Date.now());

    clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      setNow(Date.now());
    }, 10);
  }

  function handleStop() {
    clearInterval(intervalRef.current);
  }

  let secondsPassed = 0;
  if (startTime != null && now != null) {
    secondsPassed = (now - startTime) / 1000;
  }

  return (
    <>
      <h1>Time passed: {secondsPassed.toFixed(3)}</h1>
      <button onClick={handleStart}>
        Start
      </button>
      <button onClick={handleStop}>
        Stop
      </button>
    </>
  );
}

State:

This is React’s primary mechanism for displaying and updating UI data.I won’t go into details about it here as I’ll create a whole post for it. I’ll explore the React code to truly understand how state functions and how to manage it.