Skip to content

Instantly share code, notes, and snippets.

@KATT
Created April 6, 2022 09:25
Show Gist options
  • Save KATT/b6e155394213a88df6de68c4fc9a4460 to your computer and use it in GitHub Desktop.
Save KATT/b6e155394213a88df6de68c4fc9a4460 to your computer and use it in GitHub Desktop.
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