useIdleUntilUrgent
React hook that enables easy use of the idle until urgent loading strategy. This strategy involves fetching resources lazily - either whenever the browser is next idle, or when you request the resources.
This hook takes a function that invokes and returns a Promise. It then returns the result when it has been loaded. In the meantime it returns null
or the fallback
value if the optional options object.
The hook uses the requestIdleCallback function supported by many modern browsers. If it is not supported then the hook uses setTimeout(fn, 5000)
The code is inspired by Philip Walton's article about the Idle Until Urgent strategy, and Josh Duff's idle-until-urgent package
Installation
$ npm i use-idle-
or
$ yarn add use-idle-
Example of loading a component
The following component will load the IdleUntilUrgentlyLoadedCompoent when the main tread is idle for the first time, or the first time we pass getNow
is true
. IdleUntilUrgentlyLoadedCompoent is displayed when it is loaded but while waiting to load or loading <div>Loading...</div>
is displayed.
; ; const Component = { const getNow onLoad = props; const IdleUntilUrgentlyLoadedComponent = ; return <IdleUntilUrgentlyLoadedComponent />;}; ;