Last active
January 9, 2025 06:12
-
-
Save srph/1b09e19be048cd46f6479b82a468161f to your computer and use it in GitHub Desktop.
React: Flash success state before reverting back to normal state
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
| 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); | |
| 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