DEV Community

Cover image for React: useState or useRef?
Luca Mellano
Luca Mellano

Posted on

React: useState or useRef?

In React, useState and useRef are two hooks that allow us to manage state and references in functional components. Here I want to describe the main differences between them:

Re-rendering
This is maybe the main difference between useState and useRef. useState triggers a re-render when its state changes. On the other hand, useRef does not cause a re-render when its current value changes. This could save a lot of time spent in unuseful re-render caused by simple state change.

Ex:

// useState
setCount(count + 1); // triggers re-render

// useRef
inputRef.current = 'Hello'; // does not trigger re-render
Enter fullscreen mode Exit fullscreen mode

Return Values
useState returns an array with the current state value and a function to update it ([value, setValue]), while useRef returns an object with a current property ({current: initialValue}).

Ex:

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

// useRef
const inputRef = useRef(null);
Enter fullscreen mode Exit fullscreen mode

Immutability vs Mutability
useState is “immutable”, meaning you must use the state setter function to modify state variables and queue a re-render. In contrast, useRef is “mutable”, allowing you to modify and update the current value outside of the rendering process.

Ex:

// useState
setCount(count + 1); // correct way to update state

// useRef
inputRef.current = 'Hello'; // correct way to update ref
Enter fullscreen mode Exit fullscreen mode

Reading Values
You can read state at any time with useState, but each render has its own snapshot of state which does not change. Conversely, with useRef, you shouldn’t read (or write) the current value during rendering.

Ex:

// useState
console.log(count); // logs the count state

// useRef
console.log(inputRef.current); // logs the current ref value (not during render)
Enter fullscreen mode Exit fullscreen mode

These differences may help us to select effectively which one use in our projects.

Top comments (0)