Created
December 15, 2021 08:54
-
-
Save JaosnHsieh/36f5941f073b056821c62f0f57ad3d66 to your computer and use it in GitHub Desktop.
useful react hook, get previous different state value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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