React Vite includes a built-in hot-module-replacement (HMR) feature that allows developers to make changes to their code and see the results in real-time without having to refresh the page. However, sometimes, the caches need to be cleared on the client-side to see the changes, and it can be done in the following ways:
import { hot } from 'react-hot-loader/root';
const App = () => {
// your component code here
}
export default hot(App);
The hot
function wraps your root component and provides a hot-reloading feature. If the cache needs to be cleared, simply add the following code to your component:
import { hot } from 'react-hot-loader/root';
const App = () => {
const clearCache = () => {
import.meta.webpack.invalidate();
};
// your component code here
return (
<div>
<button onClick={clearCache}>Clear cache</button>
</div>
);
};
export default hot(App);
When the button is clicked, the cache is cleared, and the page will be refreshed.
// vite.config.js
const { createServer } = require('vite');
module.exports = {
server: {
middlewareMode: true,
after(app) {
app.use((req, res, next) => {
if (req.url === '/clear-cache') {
res.setHeader('Cache-Control', 'no-store');
res.status(200).end();
} else {
next();
}
});
},
},
};
// App.jsx
const App = () => {
const clearCache = async () => {
await fetch('/clear-cache', { method: 'POST' });
window.location.reload();
};
// your component code here
return (
<div>
<button onClick={clearCache}>Clear cache</button>
</div>
);
};
export default App;
With this method, a new endpoint /clear-cache
is created, which sets the Cache-Control
header to no-store
, indicating that the response should not be cached. When the button is clicked, it sends a POST request to the endpoint, triggering the cache to clear and the page to refresh.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-10-28 11:00:00 +0000
Seen: 10 times
Last updated: Oct 27 '22
In what manner does react-scripts v5 manage the lasting caching created through webpack?
Why are the packages not getting installed with the npm command?
How do I shut down a WPF page and erase its cache?
How to delete cache and cookies on Flutter Web?
Does the Microsoft.Extensions.Caching.Memory.IMemoryCache provide thread safety?
How can I address the issue of NPM ERESOLVE being incapable of resolving the dependency tree?
How to resolve the issue of Puppeteer not being found in the NPM module?