how to clear browser cache in reactjs
Asked Answered
F

8

42

every time I make changes to my website and try to update those changes to the running website, I've to hard refresh browser. is there any way to do it by code

i already try to search it but most of saying it can not be done. referance post : How to programmatically empty browser cache?

**Response headers :

HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Fri, 06 Jul 2018 10:01:23 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Content-Encoding: gzip

**Request headers :

GET / HTTP/1.1
Host: --example--.com
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,hi;q=0.7
Cookie: fingerPrint=e4a9037b8f674722f414b0b59d8d663c
Fabrice answered 6/7, 2018 at 9:46 Comment(4)
By running website, do you mean your production website? If so, it would probably be a good idea to have some cache busting filenames.Coercion
Yes you can by call a ajax page give you the last page lenght if it change will refresh automaticllyLedbetter
What do your file cache headers look like?Pitchdark
Created a component where can handle build updates into your application. You can check here: npmjs.com/package/react-clear-cacheSuccessor
H
31

For this specific case what you can do is to tell the browser not to cache your page, by using below meta tags inside <head> tag: This is temporary solution and for permanent solution, you should handle this using appropriate headers sent by your API/backend.

<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>

To handle this using API/backend, you should send the appropriate headers with your resource from your back end. And again if you are trying to disable cache temporally you can do it by disabling browser cache. To do so, Follow below steps.

In your developer tools. Find network tab and disable cache. Like here in the image.

enter image description here

Hope this resolves.

Headers for caching: https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching

Hyla answered 6/7, 2018 at 10:31 Comment(3)
OP is asking to do it by code, of course he's asking this for the end-userShinbone
thanks @Shinbone I made some edits. Hopes this answer fits the op question.Hyla
Using mata no-cache tags you affect performance and make pages to load slower than they could be loaded.Redingote
M
15

Best solution that worked for me is to clear my local storage alongside with the local cache as @Wiezalditzijn suggested

I created a function that is called the first thing in “componentDidMount”.

This function checks if there is a local saved version and if it’s equivalent to the current one; thus, if they weren’t the same, it clears all local cache and saves the new version.

import packageJson from “../package.json”;

caching= ()=> {
let version = localStorage.getItem('version');
    if(version!=packageJson.version)
    {
        if('caches' in window){
         caches.keys().then((names) => {
        // Delete all the cache files
        names.forEach(name => {
            caches.delete(name);
        })
    });

    // Makes sure the page reloads. Changes are only visible after you refresh.
    window.location.reload(true);
}

      localStorage.clear();
      localStorage.setItem('version',packageJson.version);
    }
};

UPDATE 2-2-2023

This function can be initially called from "componentDidMount" or "useEffect"

Montevideo answered 27/9, 2021 at 8:29 Comment(0)
M
6

Make a style.css file in your public folder then link this CSS file in your index.html file.

Ex:

 <link rel="stylesheet" type="text/css" href="%PUBLIC_URL%/style.css?v=0.0.1" />

Always update the version of this CSS fils before doing build your code.

Mesozoic answered 19/9, 2019 at 6:25 Comment(0)
D
6

I made a simple function to remove the cache. Just call this function when you want to clear the cache.

It works for me. *Did not tested it on edge cases.

You can implement it by keeping a version number at the client and let the server send a version number. If they don't match, call the function to remove the cache. Or you can give a button to the user and let them decide to remove the cache.

export default function emptyCache(){
    if('caches' in window){
    caches.keys().then((names) => {
            // Delete all the cache files
            names.forEach(name => {
                caches.delete(name);
            })
        });

        // Makes sure the page reloads. Changes are only visible after you refresh.
        window.location.reload(true);
    }
}
Dordogne answered 4/11, 2020 at 14:14 Comment(0)
T
1

When you are doing regular build and release to PROD environment with a chunk of js files. better to use following npm react-clear-cache for your react application. This can be used to configure the cache clear pattern based on your application build version.

Trifocals answered 10/6, 2021 at 5:6 Comment(0)
C
0

It's possible, you can simply use jQuery. please take a look at the post How to programmatically empty browser cache?

Cari answered 6/7, 2018 at 9:49 Comment(2)
Created a component where can handle build updates into your application. You can check here: npmjs.com/package/react-clear-cacheSuccessor
Would you really want to add JQuery in a ReactJS app, though? I certainly wouldnt.Diploma
P
0

Even if the below answers didn't work. And you are facing a problem something like your app being cached, making the whole app display an old build then probably you can check this link https://github.com/facebook/create-react-app/issues/1910#issuecomment-355245212. After that do an npm start, it worked for me.

Plauen answered 17/9, 2018 at 15:57 Comment(1)
This suggests to unregister service workers, so it only applies for PWA.Ikon
B
0

To cache bust on browsers, the trick is we keep updating the version of the application in meta file, which never gets cached... and to seamlessly upgrade, we perform a reload on the route change so that user would feel as if they are redirecting to a different view, but in our case we are actually cache busting our application to get the new update from the build we deployed.

Let's dig in to see how its possible.

Bankable answered 6/6, 2022 at 17:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.