Skip to content

Instantly share code, notes, and snippets.

@srph
Last active July 22, 2026 18:38
Show Gist options
  • Select an option

  • Save srph/2bd0e1edb35463b330f1e2d6c5fb994c to your computer and use it in GitHub Desktop.

Select an option

Save srph/2bd0e1edb35463b330f1e2d6c5fb994c to your computer and use it in GitHub Desktop.
React: useEphemeralState - Latches a boolean flag for a short duration, then resets to `false`

what

Latches a boolean flag for a short duration, then resets to false

Useful for when an action succeeds, then you want to reset back to normal after a short while

User completes swapping X to Y: temporarily show "Success" then allow user to interact with the form again

usage

const { mutate, status } = useMutation(...)

const isSuccess = useEphemeralState(status === 'success')
import { useEffect, useRef, useState } from "react";
/**
* Latches `true` for a short duration, then resets to `false`.
* Example: const isSuccess = useEphemeralState(mutation.isSuccess)
*/
export function useEphemeralState(value: boolean, ms = 1000): boolean {
const [ephemeralValue, setEphemeralValue] = useState<boolean>(false);
const timeoutRef = useRef<number | null>(null);
useEffect(() => {
if (!value) {
setEphemeralValue(false);
return;
}
setEphemeralValue(true);
if (timeoutRef.current !== null) {
window.clearTimeout(timeoutRef.current);
}
timeoutRef.current = window.setTimeout(() => {
setEphemeralValue(false);
timeoutRef.current = null;
}, ms);
return () => {
if (timeoutRef.current !== null) {
window.clearTimeout(timeoutRef.current);
}
};
}, [value, ms]);
return ephemeralValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment