I want to print the current and previous value of a state, I have a piece of code that does the job
function App() {
const [value, setValue] = useState("");
const prevValue = useRef('')
useEffect(() => {
prevValue.current = value;
}, [value]);
return (
<div>
<input
value={value}
onChange={e => setValue(e.target.value)}
/>
<div>
Curr Value: {value}
</div>
<div>
Prev Value: {prevValue.current}
</div>
</div>
);
}
But the problem with it is if I have some other state that is being set through, say, a button, it will cause the prev value to be same as current value. I'm looking for a way to prevent this, can someone please help?
Thanks.
Updating the
refwithuseEffectworks for a single render, because therefis updated after the content has been rendered.As you can see in here, the
useEffectis triggered when value changes. This means that at the end of each render cycle,prevValue.currentequalsvalue.If another render is triggered by an unrelated update, the
refis already equal to the currentvalue, and both are re-rendered.To always maintain the
refone step behind thevalue, use an updater function when setting the state. The updater function is called with the previous state, that you can store in theref. Return the new state from the function to update the state.The the example, you can see that the the ref always equals to the previous value, even if another update (clicking the button) causes a re-render: