In this tutorial, you will learn how to reload or refresh web pages or components in react js apps using window.location.reload()
method.
React Reload or Refresh Page Example
Here are some ways to refresh or reload web pages or components:
- Using the window object
- Using React Router
- Using a custom function
Using the window object
The simplest way to use window.location.reload()
method to reload a page in a React app, Here’s an example code:
import React from 'react'; function ReloadButton() { const handleReload = () => { window.location.reload(); }; return ( <button onClick={handleReload}>Reload Page</button> ); }
Using React Router
The history
object contains a push
method that can be used to navigate to a new URL to reload the page, Here’s an example code:
import React from 'react';
import { useHistory } from 'react-router-dom';
function ReloadButton() {
const history = useHistory();
const handleReload = () => {
history.push('/');
};
return (
<button onClick={handleReload}>Reload Page</button>
);
}
Using a custom function
Implement a custom function that uses the window.location.reload()
method or the React Router history.push
method to reload the page, Here’s an example code:
import React from 'react';
import { useHistory } from 'react-router-dom';
function ReloadButton() {
const history = useHistory();
const handleReload = () => {
// Add custom functionality here
console.log('Reloading page...');
history.push('/');
};
return (
<button onClick={handleReload}>Reload Page</button>
);
}
Conclusion
In conclusion, reloading a page in a React app can be done using several methods, including using the window.location.reload()
method, the