Skip to content

Instantly share code, notes, and snippets.

@srph
Last active January 9, 2025 06:12
Show Gist options
  • Save srph/1b09e19be048cd46f6479b82a468161f to your computer and use it in GitHub Desktop.
Save srph/1b09e19be048cd46f6479b82a468161f to your computer and use it in GitHub Desktop.
React: Flash success state before reverting back to normal state

Usage

Here's an example of using this hook on top of react-query.

When your react-query mutation succeeds, we'll only flash the success state for 3 seconds until it's reverted back to normal

const isSuccess = useEphemeralState(
  mutation.isSuccess,
  3000,
);

const isError = useEphemeralState(
  mutation.isError,
  5000,
);
import { useEffect, useState } from "react";
// This allows us to control how long we can keep a state true. After the delay,
// the state will be reverted to false.
//
// For instance, we only want to flash the success state for a few seconds to the user
// as feedback for the form. After that, we'll show the form again as normal.
const useEphemeralState = (value: boolean, delay: number) => {
const [state, setState] = useState(false);
useEffect(() => {
if (!value) {
return setState(value);
}
setState(value);
const timeout = setTimeout(() => {
setState(false);
}, delay);
return () => clearTimeout(timeout);
}, [value]);
return state;
};
export { useEphemeralState };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment