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 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-infinite-scroll-optimistic

v1.0.4

Published

A React library for implementing infinite scrolling with optimistic updates

Readme

React Infinite Scroll with Optimistic Updates

A lightweight and customizable React library for implementing infinite scrolling with built-in support for optimistic updates.

Features

  • 🔄 Infinite scrolling with intersection observer
  • ✨ Built-in optimistic updates using React 19's useOptimistic
  • 📱 Fully responsive and customizable
  • 🧪 Well-tested components and hooks
  • 💡 TypeScript support
  • 🔧 Easy to integrate with any data source

Installation

npm install react-infinite-scroll-optimistic
# or
yarn add react-infinite-scroll-optimistic

Requirements

  • React 19 or higher
  • React DOM 19 or higher

Basic Usage

import { useInfiniteScroll, InfiniteScroll } from 'react-infinite-scroll-optimistic';

function MyList() {
  const scrollResult = useInfiniteScroll({
    fetchItems: async (page) => {
      const response = await fetch(`/api/items?page=${page}`);
      return response.json();
    },
  });

  return (
    <InfiniteScroll
      scrollResult={scrollResult}
      renderItem={(item, index, ref) => (
        <div key={item.id} ref={ref}>
          {item.name}
        </div>
      )}
    />
  );
}

Optimistic Updates Example

import { useInfiniteScroll, useOptimisticActions, InfiniteScroll } from 'react-infinite-scroll-optimistic';

function MyList() {
  const scrollResult = useInfiniteScroll({
    fetchItems: async (page) => {
      const response = await fetch(`/api/items?page=${page}`);
      return response.json();
    },
  });

  const [optimisticItems, addOptimisticAction] = useOptimisticActions(
    scrollResult.items,
    (state, action) => {
      switch (action.type) {
        case 'ADD_ITEM':
          return [...state, action.item];
        case 'REMOVE_ITEM':
          return state.filter(item => item.id !== action.id);
        default:
          return state;
      }
    }
  );

  const handleAddItem = async () => {
    // Show optimistic update immediately
    const optimisticItem = { id: 'temp-' + Date.now(), name: 'New Item', status: 'pending' };
    addOptimisticAction({ type: 'ADD_ITEM', item: optimisticItem });

    // Make API call
    try {
      const response = await fetch('/api/items', {
        method: 'POST',
        body: JSON.stringify({ name: 'New Item' }),
      });
      const newItem = await response.json();

      // Update actual state with server response
      scrollResult.setItems([...scrollResult.items, newItem]);
    } catch (error) {
      console.error('Failed to add item:', error);
      // Handle error, maybe revert the optimistic update
    }
  };

  return (
    <>
      <button onClick={handleAddItem}>Add Item</button>

      <InfiniteScroll
        scrollResult={scrollResult}
        renderItem={(item, index, ref) => (
          <div key={item.id} ref={ref}>
            {item.name} {item.status === 'pending' && '(Saving...)'}
          </div>
        )}
      />
    </>
  );
}

API Reference

useInfiniteScroll

function useInfiniteScroll<T>({
  fetchItems,
  initialPage,
  threshold,
  loadImmediately,
  initialItems,
}: {
  fetchItems: (page: number) => Promise<T[]>;
  initialPage?: number;
  threshold?: number;
  loadImmediately?: boolean;
  initialItems?: T[];
}): {
  items: T[];
  loading: boolean;
  error: Error | null;
  hasMore: boolean;
  loadMore: () => Promise<void>;
  lastItemRef: (node: Element | null) => void;
  reset: () => void;
  setItems: React.Dispatch<React.SetStateAction<T[]>>;
  page: number;
};

useOptimisticActions

function useOptimisticActions<T, A>(
  initialState: T[],
  updateFn: (currentState: T[], action: A) => T[]
): [T[], (action: A) => void];

InfiniteScroll

<InfiniteScroll
  scrollResult={/* result from useInfiniteScroll */}
  renderItem={(item, index, lastItemRef) => (
    /* render your item */
  )}
  loadingComponent={/* optional custom loading component */}
  errorComponent={/* optional custom error component */}
  endComponent={/* optional custom end of list component */}
  emptyComponent={/* optional custom empty list component */}
  className={/* optional class name */}
  style={/* optional inline styles */}
>
  {/* optional header content */}
</InfiniteScroll>

License

MIT