Skip to content

Instantly share code, notes, and snippets.

@JaosnHsieh
Created December 15, 2021 08:54
Show Gist options
  • Save JaosnHsieh/36f5941f073b056821c62f0f57ad3d66 to your computer and use it in GitHub Desktop.
Save JaosnHsieh/36f5941f073b056821c62f0f57ad3d66 to your computer and use it in GitHub Desktop.
useful react hook, get previous different state value
2021.12.15 useful react hooks. previous value hook
usePreviousDifferent.ts
/**
from: https://github.com/imbhargav5/rooks/blob/main/src/hooks/usePreviousDifferent.ts
from: https://github.com/imbhargav5/rooks/blob/main/src/hooks/usePreviousDifferent.ts
Why it's useful:
To get previous different status is difficult in React hooks or even class component APIs because we always get latest state/props in component.
When to use:
1. If there is a long task has 7 status, S1 ,S2 S3 and typical idel ,pending , rejected , and. resovled in n total. We wanna know what's the previous status when current status. is rejected . In plain words, which step it failed.
2. Compare previous data, let's say we have a score number value updating constantly from websocket, we wanna compare previous score to current score, let's say if current score is higher than previous score 30 points, we show confetti effect.
**/
```
import { useRef, useEffect } from 'react';
/**
* usePreviousDifferent hook for React
* It returns the past value which was different from the current one.
*
* @param currentValue The value whose previously different value is to be tracked
* @returns The previous value
*/
function usePreviousDifferent<T>(currentValue: T): T | null {
const previousRef = useRef<T | null>(null);
const previousRef2 = useRef<T | null>(null);
useEffect(() => {
previousRef2.current = previousRef.current;
previousRef.current = currentValue;
}, [currentValue]);
return currentValue === previousRef.current
? previousRef2.current
: previousRef.current;
}
export { usePreviousDifferent };
```
from:
https://github.com/imbhargav5/rooks/blob/main/src/hooks/usePreviousDifferent.ts
https://github.com/imbhargav5/rooks/blob/main/src/hooks/usePreviousDifferent.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment