use-delayed-loading
TypeScript icon, indicating that this package has built-in type declarations

1.0.17 • Public • Published

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.

Package Sidebar

Install

npm i use-delayed-loading

Weekly Downloads

0

Version

1.0.17

License

MIT

Unpacked Size

14.4 kB

Total Files

9

Last publish

Collaborators

  • miika1006