EN
React - how to refresh the page
0
points
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:
- using JavaScript,
- 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 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.
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 );