Created
April 6, 2022 09:25
-
-
Save KATT/b6e155394213a88df6de68c4fc9a4460 to your computer and use it in GitHub Desktop.
This file contains 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
import { useEffect, useState } from 'react'; | |
/** | |
* Use the last value that isn't `null` or `undefined`. | |
* Useful for instance in modals where you don't want the selected item to flicker when the modal is closed. | |
*/ | |
export function useLastNonNullableValue<T>(currentValue: T) { | |
const [value, setValue] = useState(currentValue); | |
useEffect(() => { | |
setValue((stored) => currentValue ?? stored); | |
}, [currentValue]); | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment