FrontendDeveloper.in

React question detail

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

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 (
<button onClick={() => setCount(c => c + 1)}>Increment</button>
);
}
Back to all React questions
Get LinkedIn Premium at Rs 399