How to Refresh / Reload a Component and Page in React

Published on Jul 30, 2020

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. 🙂

Comments (0)