'React how to keep track of the previous state
So I want to know the previous state to know if I want to update a value.
I set up a tiny code example and I don't get it.
import React, { useEffect, useRef, useState } from "react";
export default function App() {
return (
<div className="App">
<Counter />
</div>
);
}
function Counter() {
const [count, setCount] = useState(0);
//the useRef Hook allows you to persist data between renders
const prevCountRef = useRef();
useEffect(() => {
//assign the ref's current value to the count Hook
prevCountRef.current = count;
}, [count]); //run this code when the value of count changes
return (
<h1>
Now: {count}, before: {prevCountRef.current}
{/*Increment */}
<button onClick={() => setCount((count) => count + 1)}>Increment</button>
</h1>
);
}
What I don't get is why is prevCountRef is not the same after the setCount is set. In the useEffect I'm always saying both are equal.
Solution 1:[1]
Whenever you update the count state, the component re-renders, which causes the useEffect to be called, and update the prevCountRef to the current count value.
Remove the useEffect block, and save the current count to the ref before updating the state:
const prevCountRef = useRef(0); // initialize the prev value
<button onClick={() => setCount((count) => {
prevCountRef.current = count; // update the prev value
return count + 1;
})}>Increment</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
