How to Access the State in setTimeout
Inside a React Function Component
useState
, setTimeout
, useEffect
, useRef
, and more
This article looks at the challenge of reading the current state value inside a callback for setTimeout
or setInterval
utility functions.
useState
Let’s start by creating a simple Counter
component. It displays a counter and a button incrementing its value.
The state in this example is the counter value.
import { useState } from "react";function increment(n) {
return n + 1;
}function Counter() {
const [count, setCount] = useState(0); return (
<div>
{count}
<button
onClick={() => setCount(increment)}>
Increment
</button>
</div>
);
}export default Counter;
The useState
hook allows to defined state inside a function component. In our example, the count
variable gives access to the state and the setCount
function allows us to modify it.
setTimeout
Next, let’s try to display the state value after 2 seconds.
import { useEffect, useState } from "react";