How to Refresh / Reload a Component and Page in React

Published on July 30, 2020 40 sec read

In this article, I’m going to share how to reload a component and page in React.js. Let’s get started:

Table of Contents

  1. Refresh Page
  2. Refresh Component

Refresh Page

To refresh a page you don’t need react-router. We want to reload a page by clicking a button. Here’s the example:

App.js
import React from 'react';

function App() {
  
  function refreshPage() {
    window.location.reload();
  }
  
  return (
    <div>
      <button onClick={ refreshPage }>Refresh!</button>
    </div>
  );
}

export default App;

Refresh Component

Using this.setState() method, we’re able to refresh a component only:

MyComponent.js
import React from "react";

class MyComponent extends React.Component {

    refresh = () => {
      // re-renders the component
      this.setState({});
    };
  
    render() {
      return (
        <div>
          <button onClick={ this.refresh }>Refresh Component</button>
        </div>
      );
    }
  }
  
  export default MyComponent;

By using useState() react hook, we can reload a component too:

MyComponent.js
import React, { useState } from 'react';

function MyComponent() {

    const [value, setValue] = useState();

    const refresh = ()=>{
        // re-renders the component
        setValue({});
    }
  
    return (
      <div>
        <button onClick={ refresh }>Refresh Component</button>
      </div>
    );
  }
  
  export default MyComponent;
That’s it. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *