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

use-api-cache

v1.0.2

Published

React hook for API caching with TTL and storage options

Readme

use-api-cache

Hook React reutilizável para cache local de dados de API com suporte a TTL, fallback em erros, localStorage ou sessionStorage.

Descrição

O useCachedApi é um hook React para facilitar o armazenamento em cache de dados buscados por APIs. Ele evita chamadas repetidas desnecessárias utilizando cache local com tempo de vida (TTL), além de permitir fallback em caso de falhas na requisição.

Ideal para melhorar performance e experiência do usuário em aplicações React que consomem dados externos.

Instalação

npm install use-api-cache

Uso Básico

import { useCachedApi } from "use-api-cache";

const fetchUsuarios = async () => {
  let url_1 = `https://jsonplaceholder.typicode.com/posts/1/comments`;
  let url_2 = `https://jsonplaceholder.typicode.com/comments`;

  const res = await fetch(url_1);
  if (!res.ok) throw new Error("Erro ao buscar usuários");
  return res.json();
};

export default function MeuComponente() {
  const { data, loading } = useCachedApi({
    cacheKey: "usuarios",
    fetcher: fetchUsuarios,
    ttl: 300000, // 5 minutos
  });

  return loading ? (
    <p style={{ marginTop: 150 }}>Carregando...</p>
  ) : (
    <ul style={{ margin: 5 }}>
      {data.map((comentario: any) => (
        <li key={comentario.id}>
          Nome: {comentario.name}
          Email: {comentario.email}
          Message: {comentario.body}
        </li>
      ))}
    </ul>
  );
}

API do Hook

useCachedApi

Recebe um objeto de configuração com as seguintes propriedades:

| Propriedade | Tipo | Obrigatório | Descrição | | -------------- | -------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | cacheKey | string | Sim | Chave usada para armazenar e recuperar o cache local. | | fetcher | () => Promise<any> | Sim | Função assíncrona que retorna os dados buscados da API. | | ttl | number | Não | Tempo de vida do cache em milissegundos. Após esse tempo, o cache é invalidado e dados são buscados novamente. Default: 300000 (5 minutos) | | storageType | "localStorage" ou "sessionStorage" | Não | Define onde o cache será armazenado. Default: "localStorage" | | fallbackData | any | Não | Dados de fallback que podem ser retornados enquanto a busca é feita ou em caso de erro. |

Valores retornados pelo hook

| Nome | Tipo | Descrição | | --------- | ----------------- | ---------------------------------------------- | | data | any | Dados retornados da API ou do cache. | | loading | boolean | Indica se a requisição está em andamento. | | error | Error ou null | Erro ocorrido durante a requisição, se houver. |

Exemplo avançado

import { useCachedApi } from "use-api-cache";

const fetchProdutos = async () => {
  const response = await fetch("https://api.exemplo.com/produtos");
  if (!response.ok) throw new Error("Falha ao carregar produtos");
  return response.json();
};

export function Produtos() {
  const { data, loading, error } = useCachedApi({
    cacheKey: "produtos",
    fetcher: fetchProdutos,
    ttl: 600000, // 10 minutos
    storageType: "sessionStorage",
    fallbackData: [],
  });

  if (loading) return <div>Carregando produtos...</div>;
  if (error) return <div>Erro: {error.message}</div>;

  return (
    <div>
      <h1>Produtos</h1>
      {data.length === 0 && <p>Nenhum produto encontrado.</p>}
      <ul>
        {data.map((produto) => (
          <li key={produto.id}>
            {produto.nome} - R$ {produto.preco.toFixed(2)}
          </li>
        ))}
      </ul>
    </div>
  );
}

Contribuição

Contribuições são bem-vindas! Sinta-se à vontade para abrir issues ou pull requests.

Licença

MIT © Fernando Augusto Rodrigues de Almeida Azevedo