Sobes.tech
Middle

What is the purpose of useState and why can't we just change a variable directly or use useRef?

sobes.tech AI

Answer from AI

useState in React is used to manage the component's state and automatically trigger a re-render when this state changes. If you simply change a variable directly, React won't recognize the change and won't update the UI.

useRef stores a mutable value, but changing the ref does not trigger a component re-render, so it is used for storing data that does not affect the rendering (e.g., timers, DOM elements).

Example:

import React, { useState, useRef } from 'react';

function Counter() {
  const [count, setCount] = useState(0); // change triggers re-render
  const countRef = useRef(0); // change does not trigger re-render

  const incrementState = () => setCount(count + 1);
  const incrementRef = () => { countRef.current += 1; console.log(countRef.current); };

  return (
    <div>
      <p>State count: {count}</p>
      <button onClick={incrementState}>Increment State</button>
      <button onClick={incrementRef}>Increment Ref</button>
    </div>
  );
}

Here, clicking "Increment State" causes the component to re-render and update the UI, while clicking "Increment Ref" only changes the value in ref, and the UI does not update.