Languages
[Edit]
EN

React - how to refresh the page

3 points
Created by:
Rubi-Reyna
677

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.

Note:

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>
    </div>
  );
};

export default App;

2. Refresh the page by updating the state

In the below code we create a counter that update causes App component re-rendering with a new state (something like page refreshing). That approach requires to pass couter to child componentes when memo() is used. We can do it with props or contexts. This approach is not recommended because can lead to complicated code structure when many componets are nested.

Note:

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>
	  <div>Counter: {counter}</div>
	  <button onClick={() => setCounter(counter + 1)}>increment</button>
	</div>
  );
};

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

References

Alternative titles

  1. React - how to reload the page
  2. React - how to reload the documment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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.

❤️💻 🙂

Join