by Sai gowtham

How to refresh a Page 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:

Home.js
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.

App.js
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>
  );
}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course