Search⌘ K

Locating the Current Value Example

Explore how to retrieve the latest values in React components using the useRef hook. Understand the limitations of useState with asynchronous updates and learn how useRef enables direct, immediate value tracking. This lesson helps you handle event-driven state changes more effectively by comparing refs and managed state approaches.

Retrieving the latest value

The current property being current is the unique thing about a ref. The property name current under the ref is given for a reason because, technically, there's nothing more current than a ref in React.

When we use a useState hook, we want to find out the current updated value of a state. Although we use the same word, current, the state can't be that current in some situations. We will use an example to demonstrate that.

Asynchronous state updates with useState

Let's say we have a button to increment a count, but instead of incrementing it right away, it waits for 3 seconds after the click:

function Title() {
// Declare a state variable 'count' with an initial value of 0 and a function 'setCount' to update it
const [count, setCount] = useState(0);
// Log a message indicating the click event after 3 sec. and the current value when the button is clicked
const onClick = () => {
setTimeout(() => {
console.log('clicked', count); // ➀
setCount(count + 1);
}, 3000);
}
// Log a message indicating the updated value of 'count' ➁
console.log('updated', count);
// Return a button element with an onClick event listener that triggers the onClick function
return <button onClick={onClick}>+</button>;
}
React functional component showcasing asynchronous state update and delayed event logging

In the code above, setTimeout is used in the event handler to deliberately delay the setCount function by 3 seconds. What we expect to see is that each click should behave like a delayed click where the count value increments to 1, 2, and 3 on the screen 3 seconds later.

When we run the code, it shows differently, as shown in the next timeline:

|--------------0-0--0----> clicked ➀
0---------------1-1--1---> updated ➁

After we click the buttons three times in a row and wait for 3 seconds, we don't see count incremented to 3 on screen. Instead, we see it incremented to 1. Quite surprising? ...