import { useState, useEffect} from "react";
export default function App() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
console.log(" ", count);
}, 3000);
}, []);
return (
<div className="App">
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Click Me </button>
</div>
);
}
The above code will display the value of count when the component renders. In the meantime if we click the button and try to change the value of count. The value of count changes but the log will contain the value zero. This also happens when you are working with async function.
We can get around this problem by using useRef hook. The code is as follows.
import { useState, useEffect, useRef } from "react";
export default function App() {
const [count, setCount] = useState(0);
const countRef = useRef(0);
countRef.current = count;
useEffect(() => {
setTimeout(() => {
console.log("useRef", countRef.current);
}, 3000);
}, []);
return (
<div className="App">
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Click Me </button>
</div>
);
}
using the above block of code we can get the current value of the variable while logging it to the console
Top comments (0)