Browser Caching
Temporary storage space on memory or hard disk, including recently downloaded web assets (js, css, images).
Introduction
Browsers store resources in their own way. When a website is first loaded in a user's browser, the browser decides to cache some resources (mainly assets like images, JS, CSS, etc.), and the browser caches the resource locally. Clearing a user's browser cache has always been a bit of a hassle, as we have no control over the user's browser. Using caching headers and build tools like Webpack that generate unique chunks for each build makes things a little easier to manage, but it's still not without its pitfalls.
How to resolve caching issue in react
- Generate a meta.json file with the app version on each build
- Fetch meta.json on load and compare versions
- Force clear cache and hard reload when there's a version mismatch
All these can be achieved by using a simple npm package,i.e, react-cache-buster
React Cache Busting
- First of all, install this package by using either npm or yarn.
npm
npm install react-cache-buster
yarn
yarn add react-cache-buster
- Now include the script for generating the meta-tags in your package.json file
package.json
"generate-meta-tag": "node ./node_modules/react-cache-buster/dist/generate-meta-tag.js"
- We need to make sure that on every build our generate-meta-tag script should run, in order to update the meta.json file (use either npm or yarn as per your package manager's choice)
package.json
"scripts": {
"build": " npm run / yarn generate-meta-tag && react-scripts build"
}
Now the last step is to wrap your App component to the CacheBusting component.
import CacheBuster from 'react-cache-buster';
import { version } from '../package.json';
<CacheBuster
currentVersion={version}
isEnabled={isProduction} //If false, the library is disabled.
isVerboseMode={false} //If true, the library writes verbose logs to console.
loadingComponent={<Loading />} //If not pass, nothing appears at the time of new version check.
>
//Your actual root component...
</CacheBuster>
Now, on every build your project assets will be appended with some tags which will be mapped with your version, so make sure to update your project's version on every release.