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

use-optimistic-reducer

v1.3.3

Published

React reducer hook for handling optimistic UI updates and race-conditions.

Downloads

39

Readme

use-optimistic-reducer

npm version License: MIT npm bundle size David

React reducer hook for handling optimistic UI updates and race-conditions.

Installation

With npm:

$ npm install use-optimistic-reducer

With yarn:

$ yarn add use-optimistic-reducer

How It Works

Internally, useOptimisticReducer uses the React.useReducer() hook to handle its state. You can use useOptimisticReducer to update the state by dispatching an action.

Whenever you need to make an optimistic UI update, you simply need to add another property named as optimistic inside your action object.

By default, a queue is formed whenever a new action is being dispatched. If an action of the same type is dispatched, this action's callback will be put into the queue and wait until all the previous callbacks to be executed.

If you wish to put your callbacks onto a separate queue, you may define a string as the identifier for the queue.

An example of an optimistic action object would look like this:

const action = {
  type: "ADD_TODO",
  payload: {},
  optimistic: {
    callback: async () => {},
    fallback: (prevState) => {}, // (Optional)
    queue: "" // (Optional)
  }
}

The optimistic property

| Name | Required | Default | Type | Description | | ------------------------- | -------- | ------- | ---- | ------------| | callback | yes | | Function | Callback function that will be called in the background. It should be an asynchronous function. | | fallback | no | | Function(prevState) | Fallback function that will be called when callback throws an error. prevState is the previous state before the error occurred. | | queue | no | action.type | string | Identifier that will be used to execute callbacks on separate queues |

Example Usage

Live Demo

import React from "react";
import useOptimisticReducer from "use-optimistic-reducer";

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case "reset":
      return action.payload;
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    case "double-increment":
      return { count: state.count + 2 };
    case "double-decrement":
      return { count: state.count - 2 };
    default:
      return state;
  }
}

function App() {
  // Define your reducer the same way you would for React.useReducer()
  const [state, dispatch] = useOptimisticReducer(reducer, initialState);

  // optimistic actions
  const doubleIncAction = {
    type: "double-increment",
    optimistic: {
      callback: () => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log("This is a callback from double-increment");
            resolve();
          }, 3000);
        });
      },
      fallback: (prevState) => {
        alert("Failed!");
        dispatch({ type: "reset", payload: prevState });
      },
      queue: "double"
    }
  };

  const doubleDecAction = {
    type: "double-decrement",
    optimistic: {
      callback: () => {
        return new Promise(resolve => {
          setTimeout(() => {
            console.log("This is a callback from double-decrement");
            resolve();
          }, 3000);
        });
      },
      fallback: (prevState) => {
        alert("Failed!");
        dispatch({ type: "reset", payload: prevState });
      },
      queue: "double"
    }
  };

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch(doubleIncAction)}>++</button>
      <button onClick={() => dispatch(doubleDecAction)}>--</button>
    </>
  );
}