npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

web-api-hooks

v3.0.2

Published

Essential set of React Hooks for convenient Web API consumption.

Downloads

8,350

Readme

web-api-hooks

Essential set of React Hooks for convenient Web API consumption.

Key features

Being part of the @kripod/react-hooks project, this package is:

  • 🌳 Bundler-friendly with tree shaking support
  • 📚 Well-documented and type-safe interfaces
  • ⚛️ Zero-config server-side rendering capability
  • 📦 Self-contained, free of runtime dependencies

Usage

After installing the package, import individual hooks as shown below:

import { useGeolocation, useLocalStorage } from 'web-api-hooks';

Sandbox

👉 Explore the API with working examples

Reference

Table of Contents

Sensors

useColorSchemePreference

Tracks color scheme preference of the user.

Examples
function Component() {
  const preferDarkMode = useColorSchemePreference() === 'dark';
  // ...
}

Returns ("light" | "dark") Preferred color scheme.

useDeviceMotion

Tracks acceleration and rotation rate of the device.

Examples
function Component() {
  const { acceleration, rotationRate, interval } = useDeviceMotion();
  // ...
}

Returns EventArgs<DeviceMotionEvent> Own properties of the last corresponding event.

useDeviceOrientation

Tracks physical orientation of the device.

Examples
function Component() {
  const { alpha, beta, gamma } = useDeviceOrientation();
  // ...
}

Returns EventArgs<DeviceOrientationEvent> Own properties of the last corresponding event.

useDocumentReadiness

Tracks loading state of the page.

Examples
function Component() {
  const documentReadiness = useDocumentReadiness();
  if (documentReadiness === 'interactive') {
    // You may interact with any element of the document from now
  }
  // ...
}

Returns DocumentReadyState Readiness of the document, which is 'loading' by default.

useDocumentVisibility

Tracks visibility of the page.

Examples
function Component() {
  const documentVisibility = useDocumentVisibility();
  if (documentVisibility === 'hidden') {
    // Reduce resource utilization to aid background page performance
  }
  // ...
}

Returns VisibilityState Visibility state of the document, which is 'visible' by default.

useFocus

Tracks focus state of an element.

Examples
function Component() {
  const [isFocused, bindFocus] = useFocus();
  // ...
  return <ElementToObserve {...bindFocus} />;
}

Returns [boolean, Readonly<{onFocus: function (): void, onBlur: function (): void}>] Whether the element has focus, and props to be spread over the element under observation.

useGeolocation

Tracks geolocation of the device.

Parameters
  • options PositionOptions? Additional watching options.
  • errorCallback function (error: PositionError): void? Method to execute in case of an error, e.g. when the user denies location sharing permissions.
Examples
function Component() {
  const geolocation = useGeolocation();
  if (geolocation) {
    const { coords } = geolocation;
  }
  // ...
}

Returns (Position | undefined) Locational data, or undefined when unavailable.

useHover

Tracks hover state of an element.

Parameters
  • disallowTouch boolean Determines whether touch gestures should be ignored. (optional, default false)
Examples
function Component() {
  const [isHovered, bindHover] = useHover();
  // ...
  return <ElementToObserve {...bindHover} />;
}

Returns [boolean, Readonly<{onMouseEnter: function (): void, onMouseLeave: function (): void, onTouchStart: function (): void, onTouchEnd: function (): void}>] Whether the element is hovered, and props to be spread over the element under observation.

useLanguagePreferences

Tracks language preferences of the user.

Examples
function Component() {
  const preferredLanguages = useLanguagePreferences();
  // ...
}

Returns ReadonlyArray<string> An array of BCP 47 language tags, ordered by preference with the most preferred language first.

useMedia

Tracks match state of a media query.

Parameters
  • query string Media query to parse.
Examples
function Component() {
  const isWidescreen = useMedia('(min-aspect-ratio: 16/9)');
  // ...
}

Returns boolean true if the associated media query list matches the state of the document, or false otherwise.

useMotionPreference

Tracks motion intensity preference of the user.

Examples
function Component() {
  const preferReducedMotion = useMotionPreference() === 'reduce';
  // ...
}

Returns ("no-preference" | "reduce") Preferred motion intensity.

useMouseCoords

Tracks mouse position.

Examples
function Component() {
  const [mouseX, mouseY] = useMouseCoords();
  // ...
}

Returns Readonly<[number, number]> Coordinates [x, y], falling back to [0, 0] when unavailable.

useNetworkAvailability

Tracks information about the network's availability.

⚠️ This attribute is inherently unreliable. A computer can be connected to a network without having internet access.

Examples
function Component() {
  const isOnline = useNetworkAvailability();
  // ...
}

Returns boolean false if the user agent is definitely offline, or true if it might be online.

useNetworkInformation

Tracks information about the device's network connection.

⚗️ The underlying technology is experimental. Please be aware about browser compatibility before using this in production.

Examples
function Component() {
  const networkInformation = useNetworkInformation();
  if (networkInformation) {
    const { effectiveType, downlink, rtt, saveData } = networkInformation;
  }
  // ...
}

Returns (NetworkInformation | undefined) Connection data, or undefined when unavailable.

useSize

Tracks size of an element.

⚗️ The underlying technology is experimental. Please be aware about browser compatibility before using this in production.

Parameters
  • ref React.RefObject<HTMLElement> Attribute attached to the element under observation.
  • ResizeObserverOverride TypeOf<ResizeObserver> Replacement for window.ResizeObserver, e.g. a polyfill.
Examples
function Component() {
  const ref = useRef < HTMLElement > null;
  const [width, height] = useSize(ref);
  // ...
  return <ElementToObserve ref={ref} />;
}

Returns Readonly<[number, number]> Dimensions [width, height], falling back to [0, 0] when unavailable.

useViewportScale

Tracks visual viewport scale.

⚗️ The underlying technology is experimental. Please be aware about browser compatibility before using this in production.

Examples
function Component() {
  const viewportScale = useViewportScale();
  // ...
}

Returns number Pinch-zoom scaling factor, falling back to 0 when unavailable.

useViewportScrollCoords

Tracks visual viewport scroll position.

⚗️ The underlying technology is experimental. Please be aware about browser compatibility before using this in production.

Examples
function Component() {
  const [viewportScrollX, viewportScrollY] = useViewportScrollCoords();
  // ...
}

Returns Readonly<[number, number]> Coordinates [x, y], falling back to [0, 0] when unavailable.

useViewportSize

Tracks visual viewport size.

⚗️ The underlying technology is experimental. Please be aware about browser compatibility before using this in production.

Examples
function Component() {
  const [viewportWidth, viewportHeight] = useViewportSize();
  // ...
}

Returns Readonly<[number, number]> Dimensions [width, height], falling back to [0, 0] when unavailable.

useWindowScrollCoords

Tracks window scroll position.

Examples
function Component() {
  const [windowScrollX, windowScrollY] = useWindowScrollCoords();
  // ...
}

Returns Readonly<[number, number]> Coordinates [x, y], falling back to [0, 0] when unavailable.

useWindowSize

Tracks window size.

Examples
function Component() {
  const [windowWidth, windowHeight] = useWindowSize();
  // ...
}

Returns Readonly<[number, number]> Dimensions [width, height], falling back to [0, 0] when unavailable.

Storage

useLocalStorage

Stores a key/value pair statefully in localStorage.

Parameters
  • key string Identifier to associate the stored value with.
  • initialValue (T | function (): T | null) Value used when no item exists with the given key. Lazy initialization is available by using a function which returns the desired value. (optional, default null)
  • errorCallback function (error: (DOMException | TypeError)): void? Method to execute in case of an error, e.g. when the storage quota has been exceeded or trying to store a circular data structure.
Examples
function Component() {
  const [visitCount, setVisitCount] =
    useLocalStorage < number > ('visitCount', 0);
  useEffect(() => {
    setVisitCount((count) => count + 1);
  }, []);
  // ...
}

Returns [T, React.Dispatch<React.SetStateAction<T>>] A statefully stored value, and a function to update it.

useSessionStorage

Stores a key/value pair statefully in sessionStorage.

Parameters
  • key string Identifier to associate the stored value with.
  • initialValue (T | function (): T | null) Value used when no item exists with the given key. Lazy initialization is available by using a function which returns the desired value. (optional, default null)
  • errorCallback function (error: (DOMException | TypeError)): void? Method to execute in case of an error, e.g. when the storage quota has been exceeded or trying to store a circular data structure.
Examples
function Component() {
  const [name, setName] = useSessionStorage < string > ('name', 'Anonymous');
  // ...
}

Returns [T, React.Dispatch<React.SetStateAction<T>>] A statefully stored value, and a function to update it.

Scheduling

useEventListener

Listens to an event while the enclosing component is mounted.

Parameters
  • target EventTarget Target to listen on, possibly a DOM element or a remote service connector.
  • type string Name of event (case-sensitive).
  • callback EventListener Method to execute whenever the event fires.
  • options AddEventListenerOptions? Additional listener characteristics.
Examples
function Component() {
  useEventListener(window, 'error', () => {
    console.log('A resource failed to load.');
  });
  // ...
}

Returns void

useInterval

Repeatedly calls a function with a fixed time delay between each call.

📝 Timings may be inherently inaccurate, due to the implementation of setInterval under the hood.

Parameters
  • callback function (): void Method to execute periodically.
  • delayMs (number | null) Time, in milliseconds, to wait between executions of the specified function. Set to null for pausing.
Examples
function Component() {
  useInterval(() => {
    // Custom logic to execute each second
  }, 1000);
  // ...
}

Returns void

Performance tips

  • Avoid layout thrashing by debouncing or throttling high frequency events, e.g. scrolling or mouse movements

  • Move non-primitive hook parameters to an outer scope or memoize them with useMemo, e.g.:

    const geolocationOptions = { enableHighAccuracy: true };
    function Component() {
      const geolocation = useGeolocation(geolocationOptions);
      // ...
    }