Skip to content

usePreviousDistinct

Category
Export Size
199 B
Last Changed
5 days ago

Just like usePrevious, but it only moves once the value actually changes.

Demo

Usage

tsx
import { 
usePreviousDistinct
} from '@reause/shared'
const
previous
=
usePreviousDistinct
(count) // `undefined` until `count` changes

The reported value is the previously committed value, updated only when the comparator says the two differ, and undefined on the first render. An unchanged re-render is not a change, so previous never becomes a copy of the current value. The comparison happens during render, not in an effect, so the pass that sees a new value is also the pass that reports the old one.

You can also provide a way of identifying the value as unique. By default, a strict equality (prev === next) is used.

tsx
import { 
usePreviousDistinct
} from '@reause/shared'
const
previousRounded
=
usePreviousDistinct
(count, (
prev
,
next
) =>
Math
.
round
(
prev
?? 0) ===
Math
.
round
(
next
))

compare receives the last value the hook accepted as distinct — not necessarily the one it returned — as its first argument, and the value being rendered now as its second. The exported Predicate<T> type describes that signature.

Type Declarations

ts
export type Predicate<T> = (prev: T | undefined, next: T) => boolean

export function usePreviousDistinct<T>(value: T, compare?: Predicate<T>): T | undefined

Source

Source · Demo

Contributors

hairyf

Changelog

v0.1.7 on
10c2b - feat(shared): add usePreviousDistinct (#927)

Released under the MIT License. v0.1.8