Skip to main content

usePrevious

A custom hook that returns the value of its argument from the previous render.

It stores the previous value whenever the current value changes, and returns that previous value when the component re-renders.


Code​

🔗 View source code


Interface​

typescript
function usePrevious<T>(value: T): T;

Parameters​

NameTypeDescription
valueTThe current value whose previous value should be tracked

Usage​

typescript
import { useState } from 'react';
import { usePrevious } from '@modern-kit/react';

const Example = () => {
const [count, setCount] = useState(0);
const previousCount = usePrevious(count);

const onIncrementCount = () => {
setCount(count + 1);
};

return (
<div>
<div>Current Count is - {count}</div>
<div>Previous Count is - {previousCount}</div>
<button onClick={onIncrementCount}>Increment</button>
</div>
);
};

Example​

Current Count is - 0
Previous Count is - 0