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-browser-cache

v1.2.2

Published

A React hook which manages a localforage instance you can use to persist data in your web applications.

Downloads

6

Readme

use-browser-cache

A React hook which manages a localforage instance you can use to persist data in your web applications.

NPM JavaScript Style Guide

Install

npm install --save use-browser-cache

Usage

You can play with an example here or just look at the code:

import React, { useEffect, useState } from "react";
import { useBrowserCache } from "use-browser-cache";

export function Component({ userId }) {
  // Don't render `useBrowserCache` in all your components.  localforage has to "connect"
  // to the browser storage APIs asynchronously. Instead, initialize the browser cache hook
  // once when the app boots and pass it as a prop to children and/or functions who need it.
  const browserCache = useBrowserCache();
  const { error, isLoading, posts = [] } = useFetchPosts(userId, browserCache);

  return (
    <ul>
      {error && <ErrorMessage error={error} />}
      {isLoading && <LoadingSpinner message="Fetching posts" />}
      {posts.map((post) => (
        <li key={post.id}>{post.content}</li>
      ))}
    </ul>
  );
}

function useFetchPosts(userId, browserCache) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setIsLoading] = useState(null);
  const [posts, setPosts] = useState(null);

  try {
    setIsLoading(true);
    setError(null);
    const cachedPosts = await browserCache.getItemAsync("posts");
    if (cachedPosts) {
      setPosts(cachedPosts);
      // Serve the cached posts and then fetch fresh posts in the background
      fetchPosts(userId).then((posts) => setPosts(posts));
      return;
    }
    // When there are no cached posts
    const posts = await fetchPosts(userId);
    setPosts(posts);
  } catch (error) {
    setError(error);
  } finally {
    setIsLoading(false);
  }
  return {
    hasError,
    isLoading,
    posts,
  };
}

Burning Questions

Burning Questions

How does this work?

This hook wraps localforage, a great library helping developers persist data using various browser persistence APIs.

When should this hook be used?

This hook is ideal for caching data which is not particularly sensitive. Additionally, your application will have to not mind serving stale data. For instance, if my app has to query the network to get a list of navigation items, you can make your UI snappier by serving cached content and fetching the items in the background. Then, when the network request has resolved, you can update the navigation items in the cache as well as those presented to the user (which probably didn't even change).

This is in the spirit of a caching strategy called "stale-while-revalidate," which means you serve stale content while a network request resolves. Some great projects like React Query or Zeit's useSWR do this, but with an ephemeral in-memory cache which is wiped at page refresh.

This hook is very general and can be what you make it.

When should this hook not be used?

As with local storage, don't put anything sensitive into browser stores (like JWTs). As you are using JavaScript to set/get those items, it is clear that they are accesible via JavaScript and are prime targets for XSS attacks.

License

MIT © adnauseum


This hook is created using create-react-hook.