usePreviousDistinct
Get the previous state or prop based on the equality comparation with current value.
API​
const prevState = usePreviousDistinct(state, compareFn);
Options​
state: any (T)
(Required)- The state (or prop) value
compareFn?: (prev: T, next: T) => boolean
- Defaults to strict equal
(prev, next) => prev === next
- The function to compare the previous and next value
- Defaults to strict equal
Returns​
prevState: T (generic)
- The previous value of the state (or prop) based on the comparation with current value
- Will not affected by re-render
Examples​
http://localhost:3000/
Count: 0
Previous count: undefined
- JS
- TS
import { useState } from 'react';
import { usePreviousDistinct } from 'react-power-ups';
export function Demo() {
const [count, setCount] = useState(0);
const increment = () => setCount((prev) => prev + 1);
const prevCount = usePreviousDistinct(count);
const [, triggerReRender] = useState(0);
return (
<>
<div>Count: {count}</div>
<button onClick={increment}>Increment</button>
<div>Previous count: {prevCount ?? <i>undefined</i>}</div>
<button onClick={() => triggerReRender(Math.random())}>Trigger Re-Render</button>
</>
);
}
import { useState } from 'react';
import { usePreviousDistinct } from 'react-power-ups';
export function Demo() {
const [count, setCount] = useState(0);
const increment = () => setCount((prev) => prev + 1);
const prevCount = usePreviousDistinct(count);
const [, triggerReRender] = useState(0);
return (
<>
<div>Count: {count}</div>
<button onClick={increment}>Increment</button>
<div>Previous count: {prevCount ?? <i>undefined</i>}</div>
<button onClick={() => triggerReRender(Math.random())}>Trigger Re-Render</button>
</>
);
}
Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-previous-distinct.ts