DEV Community

daribock
daribock

Posted on

useState vs useRef — what should I use?

When working with React hooks, useState and useRef can look similar at first — both store values.
The key difference is whether React should re-render when the value changes or not.

useState

Use useState when a value affects what the user sees.

  • Triggers a re-render when updated
  • Ideal for UI-related data (form values, counters, toggles)
const [count, setCount] = useState(0);
setCount(count + 1);
Enter fullscreen mode Exit fullscreen mode

useRef

Use useRef when you need to store a value without re-rendering the component.

  • Does NOT trigger a re-render
  • Perfect for DOM access for example to focus a HTML element
const inputRef = useRef<HTMLInputElement>(null);
inputRef.current?.focus();
Enter fullscreen mode Exit fullscreen mode

Rule of thumb

If the value changes and the UI should react → use useState
If the value changes but the UI doesn’t care → use useRef

Top comments (0)