Skip to content

usePrevious

Edit on GitHub
@volvo-cars/react-utils v1.3.0

Returns the value a prop or state variable held during the previous render. On the first render it returns undefined.

Compare the current and previous values to decide the direction of a transition:

import { usePrevious } from '@volvo-cars/react-utils';
function Carousel({ index }: { index: number }) {
const previousIndex = usePrevious(index);
const direction =
previousIndex === undefined || index > previousIndex ? 'forward' : 'back';
return <div data-direction={direction}>{/* slides */}</div>;
}

usePrevious(value) accepts:

  • value — any value to track across renders

Returns the value from the previous render, or undefined on the first render.