React - how to refresh the page
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.
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:
xxxxxxxxxx
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;
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:
xxxxxxxxxx
//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 );