Table of Contents
You might have wondered how to reload the whole page or refresh a particular component on user action or when a certain condition is met. In this article, we will discuss in detail how to do it in React.
Project setup
Create a react app using the following command:
1npx create-react-app react-refresh-page
Hard refreshing the page in React
First, we will see how to reload the whole page. Update the App.js
with the following code:
1function App() {2 const reloadPage = () => {3 window.location.reload()4 }5 return (6 <div className="App">7 <button onClick={reloadPage}>Reload Page</button>8 </div>9 )10}1112export default App
Now if you run the app and click on Reload Page button, the page will be refreshed.
Soft reloading the component when the state is changed
As you can see from the above example, when we call window.location.reload()
,
the whole page reloads and downloads all the resources (css, js, etc) from the server.
This may not be a great user experience, especially on slower networks.
We can reload only the components that need to be refreshed by updating the state.
Consider the following code:
1import { useState } from "react"23function App() {4 const [counter, setCounter] = useState(0)56 return (7 <div className="App">8 <div>Count is {counter}</div>9 <button onClick={() => setCounter(counter + 1)}>Update Counter</button>10 </div>11 )12}1314export default App
Here, the counter is updated every time the user clicks on the Update Counter button, the page is refreshed and the updated counter value is shown.
The refresh happens instantly without reloading all the resources, which is a great user experience.
Refreshing the page at specific intervals
We can refresh the component at specific intervals using setInterval API and useEffect hook.
1import { useEffect, useState } from "react"23function App() {4 const [counter, setCounter] = useState(0)56 useEffect(() => {7 let interval89 const updateCounter = () => {10 setCounter(currentValue => currentValue + 1)11 }1213 interval = setInterval(() => {14 updateCounter()15 }, 1000)1617 return () => {18 // Clear the interval when component is unmounted19 clearInterval(interval)20 }21 }, [])2223 return (24 <div className="App">25 <div>Count is {counter}</div>26 </div>27 )28}2930export default App
In the above code, the page is refreshed every second and shows the updated counter.
Do follow me on twitter where I post developer insights more often!