usePrevious
A hook that allows to retrieve the previous value of a value
Example
import { useState } from "react";
import usePrevious from "@/hooks/usePrevious";
export default function UsePreviousExample() {
const [input, setInput] = useState("");
const previousInput = usePrevious(input);
return (
<div className="text-ctp-text">
<input
type="text"
value={input}
placeholder="Type something..."
className="rounded bg-ctp-surface1 p-2"
onChange={(event) => {
setInput(event.target.value);
}}
/>
<p>Current input: {input}</p>
<p>Previous input: {previousInput}</p>
</div>
);
}
Code
import { useState } from "react";
/**
* A hook that allows to retrieve the previous value of a value
* @returns {T | null} returns the previous value or null if the value hasn't changed
*/
export default function usePrevious<T>(value: T): T | null {
const [current, setCurrent] = useState(value);
const [previous, setPrevious] = useState<null | T>(null);
if (value !== current) {
setPrevious(current);
setCurrent(value);
}
return previous;
}