React & Modern Frontend (445 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
Can useRef be used to store previous values?
Yes, useRef is a common pattern when you want to compare current and previous props or state without causing re-renders.
Example: Storing previous state value
js
import { useEffect, useRef, useState } from 'react';
function PreviousValueExample() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count;
}, [count]);
const prevCount = prevCountRef.current;
return (
<div>
<p>Current: {count}</p>
<p>Previous: {prevCount}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
</div>
);
}