File size: 1,406 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# `usePreviousDistinct`

Just like `usePrevious` but it will only update once the value actually changes. This is important when other
hooks are involved and you aren't just interested in the previous props version, but want to know the previous
distinct value

## Usage

```jsx
import {usePreviousDistinct, useCounter} from 'react-use';

const Demo = () => {
  const [count, { inc: relatedInc }] = useCounter(0);
  const [unrelatedCount, { inc }] = useCounter(0);
  const prevCount = usePreviousDistinct(count);

  return (
    <p>
      Now: {count}, before: {prevCount}
      <button onClick={() => relatedInc()}>Increment</button>
      Unrelated: {unrelatedCount}
      <button onClick={() => inc()}>Increment Unrelated</button>
    </p>
  );
};
```

You can also provide a way of identifying the value as unique. By default, a strict equals is used.

```jsx
import {usePreviousDistinct} from 'react-use';

const Demo = () => {
  const [str, setStr] = React.useState("something_lowercase");
  const [unrelatedCount] = React.useState(0);
  const prevStr = usePreviousDistinct(str, (prev, next) => (prev && prev.toUpperCase()) === next.toUpperCase());

  return (
    <p>
      Now: {count}, before: {prevCount}
      Unrelated: {unrelatedCount}
    </p>
  );
};
```

## Reference

```ts
const prevState = usePreviousDistinct = <T>(state: T, compare?: (prev: T | undefined, next: T) => boolean): T;
```