Hackforge Academy

Category: react

State vs Ref: The Core Difference

Published on 27 Oct 2026

Explanation

State stores data that affects what the UI displays and causes a rerender when updated. A ref stores a mutable value that persists between renders but changing it does not trigger a rerender.

Code:

const [count, setCount] = useState(0);
const renderCount = useRef(0);

function increment() {
  setCount((value) => value + 1); // Rerenders
  renderCount.current += 1;       // Does not rerender by itself
}

Explanation

Attach a ref to a DOM element when you need to focus it, measure it, or interact with it imperatively.

Code:

const inputRef = useRef(null);

function focusInput() {
  inputRef.current?.focus();
}

return <input ref={inputRef} />;

Explanation

A timer ID usually does not belong in rendered state. A ref is a convenient place to store it so a handler can clear the timer without causing a rerender.

Code:

const timerRef = useRef(null);

function startTimer() {
  timerRef.current = setTimeout(() => {
    console.log('Finished');
  }, 1000);
}

function stopTimer() {
  clearTimeout(timerRef.current);
}

Explanation

A ref can retain a value from the previous render. Update it after rendering in an effect when you want to compare the current value with the previous one.

Code:

const previousName = useRef(name);

useEffect(() => {
  previousName.current = name;
}, [name]);

// During render, previousName.current holds the value
// saved by the preceding effect.

Explanation

Do not use refs for values that need to appear in the UI. Since changing ref.current does not rerender the component, use state for visible values such as selected tabs, form messages, and counters.

Code:

const [message, setMessage] = useState('');

function showMessage() {
  setMessage('Saved successfully');
}

return <p>{message}</p>;

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community