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

v1.0.3

Published

A simple modern utility to clear cache and reload the application.

Readme

React Cache Refresh 🚀

A modern, lightweight React utility that automatically detects new app versions and clears browser caches to ensure users always get the latest version of your application.

✨ Features

  • Automatic Version Detection: Compares current app version with latest deployed version
  • Smart Cache Clearing: Clears all browser caches (Service Worker caches, HTTP caches)
  • React 19 Compatible: Built with modern React patterns and hooks
  • TypeScript Support: Full TypeScript support with type definitions
  • Reload Protection: Prevents infinite reload loops with built-in cooldown mechanism
  • Error Resilient: Gracefully handles missing meta.json or network errors
  • Configurable Logging: Hide console logs in production with hideConsoleLogs option
  • Custom Loading States: Show custom loading components during version checks
  • Zero Dependencies: Only requires React as a peer dependency

📦 Installation

npm install react-cache-refresh
# or
yarn add react-cache-refresh
# or
pnpm add react-cache-refresh

🚀 Quick Start

1. Create a meta.json file

First, create a meta.json file in your public directory with your app version:

{
  "version": "1.0.0"
}

2. Wrap your app with CacheBuster

import React from "react";
import { CacheBuster } from "react-cache-refresh";
import App from "./App";

const VERSION = "1.0.0"; // This should match your package.json version

function Root() {
  return (
    <CacheBuster
      currentAppVersion={VERSION}
      loadingComponent={<div>Loading...</div>}
    >
      <App />
    </CacheBuster>
  );
}

export default Root;

3. Update your build process

Make sure to update the meta.json file with the new version number whenever you deploy:

{
  "version": "1.0.1"
}

📖 API Reference

CacheBuster Component

The main component that wraps your application and handles version checking.

Props

| Prop | Type | Required | Default | Description | | ------------------- | ----------- | -------- | ------- | ----------------------------------------------------- | | children | ReactNode | ✅ | - | Your app components | | currentAppVersion | string | ✅ | - | Current version of your app | | loadingComponent | ReactNode | ❌ | null | Custom loading component (shown during version check) | | hideConsoleLogs | boolean | ❌ | false | Hide console logs for version checking process |

Example with Custom Loading and Options

import React from "react";
import { CacheBuster } from "react-cache-refresh";
import App from "./App";
import LoadingSpinner from "./components/LoadingSpinner";

const VERSION = "1.0.0";

function Root() {
  return (
    <CacheBuster
      currentAppVersion={VERSION}
      loadingComponent={<LoadingSpinner />}
      hideConsoleLogs={process.env.NODE_ENV === "production"}
    >
      <App />
    </CacheBuster>
  );
}

Utility Functions

clearAllCaches()

Manually clear all browser caches.

import { clearAllCaches } from "react-cache-refresh/utils";

const handleClearCache = async () => {
  try {
    await clearAllCaches();
    console.log("All caches cleared successfully");
  } catch (error) {
    console.error("Error clearing caches:", error);
  }
};

🔧 Advanced Usage

Hiding Console Logs in Production

For production environments, you might want to hide the version checking console logs:

import React from "react";
import { CacheBuster } from "react-cache-refresh";
import App from "./App";

const VERSION = "1.0.0";

function Root() {
  return (
    <CacheBuster
      currentAppVersion={VERSION}
      hideConsoleLogs={process.env.NODE_ENV === "production"}
    >
      <App />
    </CacheBuster>
  );
}

Using with Environment Variables

import React from "react";
import { CacheBuster } from "react-cache-refresh";
import App from "./App";

// Get version from environment variable or package.json
const VERSION = process.env.REACT_APP_VERSION || "1.0.0";

function Root() {
  return (
    <CacheBuster
      currentAppVersion={VERSION}
      hideConsoleLogs={process.env.NODE_ENV === "production"}
    >
      <App />
    </CacheBuster>
  );
}

Custom Loading Component

import React from "react";
import { CacheBuster } from "react-cache-refresh";
import App from "./App";

const LoadingComponent = () => (
  <div
    style={{
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
      height: "100vh",
    }}
  >
    <div>Checking for updates...</div>
  </div>
);

function Root() {
  return (
    <CacheBuster
      currentAppVersion="1.0.0"
      loadingComponent={<LoadingComponent />}
    >
      <App />
    </CacheBuster>
  );
}

Console Logging Behavior

By default, react-cache-refresh provides helpful console logs during the version checking process:

  • Version Check: Shows current and latest versions
  • Success: Confirms when versions match
  • Updates: Logs when version mismatch is detected
  • Errors: Reports any issues with version checking

Example console output:

Current app version: 1.0.0
Latest app version: 1.0.1
Version mismatch detected - clearing caches and reloading

You can disable these logs in production using the hideConsoleLogs prop:

<CacheBuster
  currentAppVersion="1.0.0"
  hideConsoleLogs={process.env.NODE_ENV === "production"}
>
  <App />
</CacheBuster>

Integration with CI/CD

Basic Example (Package.json Versioning)

# GitHub Actions
name: Deploy
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: echo '{"version":"'$(node -p "require('./package.json').version")'"}' > public/meta.json
      - run: npm ci && npm run build

Dynamic Versioning (Recommended)

Generate unique versions using Git SHA + Pipeline ID:

# GitHub Actions
name: Deploy with Dynamic Versioning
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Generate version
        run: |
          VERSION="${GITHUB_REF#refs/heads/}.$(date -u +%Y%m%d%H%M%S).$(git rev-parse --short HEAD).${{ github.run_id }}"
          echo '{"version":"'$VERSION'"}' > public/meta.json
          echo "REACT_APP_VERSION=$VERSION" > .env.production
      - run: npm ci && npm run build
// In your React app
const VERSION = process.env.REACT_APP_VERSION || "dev-local";

<CacheBuster currentAppVersion={VERSION}>
  <App />
</CacheBuster>;

GitLab CI

# .gitlab-ci.yml
build:
  script:
    - VERSION="${CI_COMMIT_REF_NAME}.$(date -u +%Y%m%d%H%M%S).${CI_COMMIT_SHORT_SHA}.${CI_PIPELINE_ID}"
    - echo "{\"version\": \"${VERSION}\"}" > public/meta.json
    - echo "REACT_APP_VERSION=${VERSION}" > .env.production
    - npm ci && npm run build

Azure DevOps

# azure-pipelines.yml
variables:
  version: $(Build.SourceBranchName).$(Build.BuildId)
steps:
  - script: |
      echo "{\"version\": \"$(version)\"}" > public/meta.json
      echo "REACT_APP_VERSION=$(version)" > .env.production
      npm ci && npm run build

Version Formats

# Examples of generated versions:
"main.20241001143022.a1b2c3d.12345"  # branch.date.sha.buildid
"20241001143022.a1b2c3d.12345"       # date.sha.buildid (shorter)
"a1b2c3d.12345"                      # sha.buildid (minimal)

Using with Webpack

// webpack.config.js
const fs = require("fs");
const packageJson = require("./package.json");

// Update meta.json during build
fs.writeFileSync(
  "public/meta.json",
  JSON.stringify({
    version: packageJson.version,
  })
);

🌐 Server Configuration

Ensure meta.json is never cached by adding these headers:

Nginx:

location /meta.json {
  add_header Cache-Control "no-cache, no-store, must-revalidate";
}

Apache:

<Files "meta.json">
  Header set Cache-Control "no-cache, no-store, must-revalidate"
</Files>

🔍 How It Works

  1. Version Check → Fetches /meta.json on app load
  2. Comparison → Compares with current app version
  3. Cache Clear → Clears all browser caches if versions differ
  4. Reload → Hard reload to get latest version
  5. Cooldown → 5-second safety to prevent reload loops

🛠️ Troubleshooting

| Issue | Solution | | ----------------------- | ------------------------------------------------------------------ | | Infinite reloads | Ensure meta.json and app versions match during deployment | | Version check fails | Check meta.json exists and isn't cached by your server | | 404 for meta.json | Component handles this gracefully - just add the file to /public |

Debug: Check browser console for version logs and error details.

🐛 Issues & Support

Found a bug or have a feature request? Please open an issue on GitHub.

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

This project is licensed under the ISC License.

🔗 Links


Made with ❤️ for the React community