spin-delay

repository·main·Indexed 20 days ago

https://github.com/smeijer/spin-delay

A smart spinner helper for React designed to prevent UI flicker and unnecessary spinner rendering during fast network requests. It provides the useSpinDelay hook to manage loading states with configurable delay and minimum duration thresholds.

Tokens
780
Snippets
4
Records
5
Agent score
19%

What's inside spin-delay

  1. Configure `SpinDelayOptions`

    main

    When calling useSpinDelay, you can provide an optional configuration object to fine-tune the spinner behavior.

    OptionTypeDefaultDescription
    delaynumber500The delay in milliseconds before the spinner is displayed.
    minDurationnumber200The minimum duration in milliseconds the spinner is displayed once it appears.
    ssrbooleantrueIf true, delay is ignored and the spinner shows immediately if loading is true (useful for Server-Side Rendering).
    interface SpinDelayOptions {
      delay?: number;
      minDuration?: number;
      ssr?: boolean;
    }
  2. How spin-delay works

    main
    The spin-delay library prevents UI flicker and unnecessary spinner rendering by wrapping boolean loading states. It ensures that a spinner is only shown if the loading state persists longer than a specified delay, and once shown, it remains visible for at least a minDuration. This prevents the
  3. Use the `useSpinDelay` hook to manage spinner visibility

    main

    The useSpinDelay hook manages the visibility of a loading spinner to prevent 'flickering' (where a spinner appears for a split second during very fast loads). It introduces a configurable delay before showing the spinner and ensures that if the spinner is shown, it stays visible for at least a minimum duration.

    Returns true when the spinner should be displayed, and false otherwise.

    State Lifecycle

    The hook internally manages four states:

    • IDLE: Not loading.
    • DELAY: Loading has started, but the delay threshold hasn't been met.
    • DISPLAY: The spinner is currently visible.
    • EXPIRE: The spinner is in its minDuration phase to prevent rapid flickering.

    Parameters

    • loading (boolean): The current loading state of your application/component.
    • options (optional): A SpinDelayOptions object to customize behavior.
    import { useSpinDelay } from 'spin-delay';
    
    function MyComponent({ isLoading }) {
      const showSpinner = useSpinDelay(isLoading, {
        delay: 500,
        minDuration: 200,
        ssr: false
      });
    
      return (
        <div>
          {showSpinner && <Spinner />}
          {isLoading ? <p>Loading...</p> : <p>Data Loaded!</p>}
        </div>
      );
    }