How to refresh the Page or Component in React
In this tutorial, we are going to learn about how to refresh a page or component in React with the help of examples.
Refreshing a page
To refresh a page, we need to use the window.location.reload()
method in React.
By default this method reloads the page from a cache, if we pass true
as an argument it reloads the entire page from a server instead of cache.
Let’s see an example:
import React from "react";
function Home() {
const refreshPage = ()=>{
window.location.reload(); }
return (
<div>
<h1>{Math.random()}</h1>
<button onClick={refreshPage}>Refresh</button> </div>
);
}
In the above code, we are refreshing the page by clicking on a refresh
button.
Refreshing a component
If you want to refresh the particular component instead of an entire page, you need to call the this.setState()
method with an empty object.
import React from "react";
class App extends React.Component {
handleRefresh = () => {
// by calling this method react re-renders the component
this.setState({}); };
render() {
return (
<div>
<h1>{Math.random()}</h1>
<button onClick={this.handleRefresh}>Refresh component</button> </div>
);
}
}
export default App;
By calling this.setState() method with an empty object react will think that something is upated in the state and component needs to be refreshed (or re-rendered) with a new UI.
Refreshing a component using hooks
In react hooks, we can use the useState()
hook to refresh the component.
import React from "react";
function Home() {
const [value,setValue] = useState();
const refresh = ()=>{
// it re-renders the component setValue({});
}
return (
<div>
<p>{Math.random()}</p>
<button onClick={refresh}>Refresh component</button>
</div>
);
}