Skip to content

⚛️ Minimal "optimistic UI" pattern implementation with a React Hook

License

Notifications You must be signed in to change notification settings

mamal72/react-optimistic-ui-hook

Repository files navigation

NPM Build Status codecov David npm npm bundle size npm

react-optimistic-ui-hook

Minimal zero dependency "optimistic UI" pattern implementation in a React Hook.

What is "Optimistic UI"?

Optimistic UIs don’t wait for an operation to finish to update to the final state. They immediately switch to the final state, showing fake data for the time while the real operation is still in-progress. Read More Here

Note that you can search for "optimistic UI" and read more about this pattern and how it works. It simply lets your app looks faster by expecting a successful call to something like an API before getting the real response and update the interface based on that expectation.

Installation

Using NPM:

npm install react-optimistic-ui-hook

Using Yarn:

yarn add react-optimistic-ui-hook

Usage

import React from 'react'
import { useOptimisticUI } from 'react-optimistic-ui-hook'

const USERNAME = 'mamal72'
const PREDICTED_AVATAR_URL = 'https://avatars0.githubusercontent.com/u/810438?v=4'
const DELAY_IN_MS = 2000

async function getGithubAvatarURL(username: string): Promise<string> {
  const response = await fetch(`https://api.github.com/users/${username}`)
  const data = await response.json()

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(data.avatar_url)
    }, DELAY_IN_MS);
  })
}

export function GithubAvatar() {
  const { status, result, error } = useOptimisticUI<string>(() => getGithubAvatarURL(USERNAME), PREDICTED_AVATAR_URL)

  if (status === 'failed') {
    // The "result" will be the predicted image url passed to the Hook,
    // But "error" is set to the raised error in the passed promise
    console.error("Failed to fetch image!", error)
  }

  if (status === 'loading') {
    // The "result" will be the predicted image passed to the Hook again!
    console.log('Loading image!')
  }

  if (status === 'succeed') {
    // The "result" will be the resolved promise response here!
    console.log("Resolved image!", result)
  }

  return (
    <div>
      <img src={result} alt="avatar" />
      <p>Status: {status}</p>
    </div>
  )
}

Contribution

You can report bugs and issues here.

You can also send a PR if you feel like you can improve or fix something. Don't forget to write/update tests for your changes.

About

⚛️ Minimal "optimistic UI" pattern implementation with a React Hook

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published