Skip to Content
UI KitHooksusePrevious

Overview

The usePrevious hook is a useful tool in React development for keeping track of the previous value of a state or prop. This hook is particularly helpful in scenarios where you need to compare the current value with its previous one, such as in animations, form changes, or data updates.

By incorporating usePrevious into your React components, you can effectively track changes in state or props across renders, enabling more sophisticated component behaviors and interactions.

Key Features

  • Previous Value Tracking: Captures and provides the previous value of a given state or prop.
  • Simple and Reusable: Can be easily integrated into any component that requires tracking of previous values.

How It Works

The hook accepts a value and uses useRef and useEffect from React to store and update the previous value whenever the provided value changes.

Syntax

const previousValue = usePrevious(value);
  • value: The current value for which the previous value is to be tracked.

Usage Example

Here’s an example of how to use the usePrevious hook:

import { useState } from 'react'; import { usePrevious } from '@akinon/ui-hooks'; const MyComponent = () => { const [count, setCount] = useState(0); const previousCount = usePrevious(count); return ( <div> <p>Current Count: {count}</p> <p>Previous Count: {previousCount}</p> <button onClick={() => setCount(prevValue => prevValue + 1)}> Increment </button> </div> ); }; export default MyComponent;