usePreviousDistinct

A utility hook that captures the last distinct value of a variable, filtering out redundant consecutive updates.

Note

This hook uses Object.is for comparison. It only updates the "previous" reference when the current value actually changes, making it ideal for tracking props or IDs.

Installation

bash

Description

The usePreviousDistinct tracks a specific value and stores its inmediate predecessor, but only when the new value differs from the current one. It acts as a specialized memory buffer that ignores identical consecutive renders, ensuring that the returned previous value is always functionally different from the current value.

Parameters

NameTypeDescription
valueT GenericThe variable or state to track for distinct changes.

Return values

NameTypeDescription
previousT Generic | undefinedThe previous value of the tracked variable.

Demo

Previous Distinct

Current
#3b82f6
Previous (Distinct)
Clicking a different color updates both.Clicking the same color twice will not change the Previous value.

Source code

tsx