Middle
import { useState } from "react"; const usePreviousValue = (value: number) => {}; export default function App() { const [count, setCount] = useState(0); const previous = usePreviousValue(count); return ( <div className="App"> <h1>Current Value: {count}</h1> <h2>Previous: {previous ?? "-"}</h2> <button onClick={() => setCount((prev) => prev + 1)}>Click</button> </div> ); }
sobes.tech AI
Answer from AI
The usePreviousValue hook is used to retain the previous value of the value variable between renders in React. It can be implemented using useRef:
import { useEffect, useRef } from "react";
const usePreviousValue = (value: number) => {
const ref = useRef<number | undefined>(undefined);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
export default function App() {
const [count, setCount] = useState(0);
const previous = usePreviousValue(count);
return (
<div className="App">
<h1>Current Value: {count}</h1>
<h2>Previous: {previous ?? "-"}</h2>
<button onClick={() => setCount((prev) => prev + 1)}>Click</button>
</div>
);
}
Here, useRef stores the value between renders, and it is updated in useEffect after each change of value. Thus, on the next render, the previous value can be accessed.