usePrevious
React hook to track the previous value of a variable.
Add the hook via the CLI:
sh
npx @novajslabs/cli add usePrevioussh
npx @novajslabs/cli add usePrevioussh
pnpm dlx @novajslabs/cli add usePreviousOr copy and paste the code into your project:
ts
import { useRef } from "react";
export const usePrevious = <T>(value: T): T | undefined => {
const currentRef = useRef<T>(value);
const previousRef = useRef<T>(undefined);
if (currentRef.current !== value) {
previousRef.current = currentRef.current;
currentRef.current = value;
}
return previousRef.current;
};js
import { useRef } from "react";
export const usePrevious = (value) => {
const currentRef = useRef(value);
const previousRef = useRef(undefined);
if (currentRef.current !== value) {
previousRef.current = currentRef.current;
currentRef.current = value;
}
return previousRef.current;
};Requirements
React 16.8 or higher
Parameters
value required
Type: T
The value to track.
Return values
previousValue
Type: T
The previous value of value.