Novice, Practiced, Mastered
    Wondering what’s next for npm?Check out our public roadmap! »

    @rest-hooks/img
    TypeScript icon, indicating that this package has built-in type declarations

    0.2.2 • Public • Published

    <Img /> - Suspenseful Image

    CircleCI Coverage Status npm downloads bundle size npm version PRs Welcome

    Suspenseful image component: <Img />.

    In many cases, it would be useful to suspend loading of expensive items like images using suspense. This becomes especially powerful with the fetch as you render pattern in concurrent mode.

    Here, we build an endpoint for images using Image

    Here, Rest Hooks is simply used to track resource loading - only storing the src in its store.

    Usage

    Profile.tsx
    import React, { ImgHTMLAttributes } from 'react';
    import { useResource } from 'rest-hooks';
    import { Img } from '@rest-hooks/img';
    
    export default function Profile({ username }: { username: string }) {
      const user = useResource(UseResource.detail(), { username });
      return (
        <div>
          <Img
            src={user.img}
            alt="React Logo"
            style={{ height: '32px', width: '32px' }}
          />
          <h2>{user.fullName}</h2>
        </div>
      );
    }

    Prefetching

    Note this will cascade the requests, waiting for user to resolve before the image request can start. If the image url is deterministic based on the same parameters, we can start that request at the same time as the user request:

    Profile.tsx
    import React, { ImgHTMLAttributes } from 'react';
    import { useResource, useRetrieve } from 'rest-hooks';
    import { Img, getImage } from '@rest-hooks/img';
    
    export default function Profile({ username }: { username: string }) {
      const imageSrc = `/profile_images/${username}}`;
      useRetrieve(getImage, { src: imageSrc });
      const user = useResource(UseResource.detail(), { username });
      return (
        <div>
          <Img
            src={imageSrc}
            alt="React Logo"
            style={{ height: '32px', width: '32px' }}
          />
          <h2>{user.fullName}</h2>
        </div>
      );
    }

    When using the fetch as you render pattern in concurrent mode, useFetcher with the getImage Endpoint to preload the image.

    Install

    npm i @rest-hooks/img

    DownloadsWeekly Downloads

    47

    Version

    0.2.2

    License

    Apache-2.0

    Unpacked Size

    63.8 kB

    Total Files

    24

    Last publish

    Collaborators

    • avatar
    • avatar