React - how to refresh the page

0 points
Created by:
Admin Dirask Community

In this article, we would like to show you how to refresh the page in React.

There are two ways to refresh the page in React:

  1. using JavaScript,
  2. updating the state.

1. Refresh the page using JavaScript

To reload the page you can use:

  • window.location.reload() - recommended,
  • window.location.href = window.location.href.

Below we create a simple component that is being refreshed when onClick event occurs.


Uncomment the second solution to see how it works.

Practical example:

import React from 'react';

const handleClick = () => {
  window.location.reload();  // recommended
  //window.location.href = window.location.href;  // not recommended

const App = () => {
  return (
    <div className="App">
      <button onClick={handleClick}>Click me</button>

export default App;

2. Refresh the page by updating the state

In the App component we create useState hook, which keeps the state of our component inside a counter. Counter update causes App component re-rendering (page refreshing) with a new state.


For more information read this article: React - useState example.

Runnable example:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
//import React from 'react';

const App = () => {
  const [counter, setCounter] = React.useState(0);
  return (
	  <div>Counter: {counter}</div>
	  <button onClick={() => setCounter(counter + 1)}>increment</button>

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );


Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé