Skip to content

Instantly share code, notes, and snippets.

@srph
Created July 22, 2026 18:36
Show Gist options
  • Select an option

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

Select an option

Save srph/cb43bad0632b8d35f2755b161702f76a to your computer and use it in GitHub Desktop.
React: useAnimationText - Rotating text for long-running pending buttons

what

Rotating text for long-running pending buttons

usage

const STOP_TEXTS = [
  "Closing Positions",
  "Canceling Orders",
  "Finalizing Trades",
  "Updating Balances",
  "Saving Session",
  "Cleaning Up",
  "Almost Done",
];

const text = useAnimationText({
  default: "Stop",
  loading: "Stopping",
  last: "Hold On",
  loop: STOP_TEXTS,
  enabled: isPending,
});
import { useEffect, useState, useMemo } from "react";
import { useInterval } from "./use-interval";
export type UseAnimationTextOptions = {
default: string;
loading: string;
loop: string[];
last?: string;
enabled: boolean;
interval?: number;
};
export function useAnimationText({
default: defaultText,
loading,
loop,
last,
enabled,
interval = 4000,
}: UseAnimationTextOptions): string {
const [index, setIndex] = useState(-1);
const [shuffleKey, setShuffleKey] = useState(0);
const shuffledLoop = useMemo(() => {
if (loop.length === 0) return loop;
const shuffled = shuffleArray(loop);
return last ? [...shuffled, last] : shuffled;
}, [loop, last, shuffleKey]);
useInterval(
() => setIndex((prev) => Math.min(prev + 1, shuffledLoop.length - 1)),
enabled && shuffledLoop.length > 0 ? interval : null,
);
useEffect(() => {
if (!enabled) {
setIndex(-1);
} else {
setIndex(-1);
setShuffleKey((prev) => prev + 1); // Trigger new shuffle each time animation starts
}
}, [enabled]);
if (!enabled) return defaultText;
if (index === -1) return loading;
return shuffledLoop[index] || loading;
}
function shuffleArray<T>(array: T[]): T[] {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment