Skip to content

Custom React Hook that will set loading = true (fe. to show loader), but with a delay.

License

Notifications You must be signed in to change notification settings

miika1006/use-delayed-loading

Repository files navigation

use-delayed-loading

Custom React Hook that will set loading = true (fe. to show loader), but with a delay.

NPM JavaScript Style Guide

When you have a random delay in a some function, for example when fetching data from server. The function can run for 10 seconds or it might finish immediatelly. When that happens, you don't want to flicker a loader in your page. Now, there are probably many solutions to this, but this is one lazy one.

Did this to test creating custom hook and publishing it to npm.

Used npx create-react-hook with typescript and yarn. Created my hook, and then published with npm.

Install

npm install --save use-delayed-loading

or

yarn add use-delayed-loading

Usage

import { useDelayedLoading } from "use-delayed-loading";

export const MyComponent: React.FC = () => {
  const [loading, setLoading] = useDelayedLoading(false);
  const loadDataFromApi = async () => {

    try{
      setLoading(true);
      const result = await fetch(...);
      ...
    }
    finally{
      setLoading(false);
    }
  }
  ...
  return loading ? "Loading" : "Hello there";
}

You can specify the delay yourself with a delay parameter that is 500 milliseconds by default.

//Change delay to 1 second
const [loading, setLoading] = useDelayedLoading(false, 1000);

License

MIT © Miika Mehtälä / miika1006


This hook is created using create-react-hook with typescript and yarn.

Releases

No releases published

Packages

No packages published