Skip to content

Instantly share code, notes, and snippets.

@srph
Last active January 9, 2025 06:12
Show Gist options
  • Select an option

  • Save srph/1b09e19be048cd46f6479b82a468161f to your computer and use it in GitHub Desktop.

Select an option

Save srph/1b09e19be048cd46f6479b82a468161f to your computer and use it in GitHub Desktop.

Revisions

  1. srph revised this gist Jan 9, 2025. No changes.
  2. srph revised this gist Jan 9, 2025. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion useEphemeralState.ts
    Original file line number Diff line number Diff line change
    @@ -10,7 +10,7 @@ const useEphemeralState = (value: boolean, delay: number) => {

    useEffect(() => {
    if (!value) {
    return;
    return setState(value);
    }

    setState(value);
  3. srph revised this gist Dec 30, 2024. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion readme.md
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,8 @@
    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
    ```

    ```tsx
    const isSuccess = useEphemeralState(
    mutation.isSuccess,
    3000,
  4. srph revised this gist Dec 30, 2024. 1 changed file with 15 additions and 0 deletions.
    15 changes: 15 additions & 0 deletions readme.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    ## 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,
    );
    ```
  5. srph created this gist Dec 30, 2024.
    28 changes: 28 additions & 0 deletions useEphemeralState.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    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 };