Skip to content
react

How to refresh a page or a component in React

Dec 2, 2022Abhishek EH2 Min Read
How to refresh a page or a component in React

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:

App.js
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}
11
12export 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:

App.js
1import { useState } from "react"
2
3function App() {
4 const [counter, setCounter] = useState(0)
5
6 return (
7 <div className="App">
8 <div>Count is {counter}</div>
9 <button onClick={() => setCounter(counter + 1)}>Update Counter</button>
10 </div>
11 )
12}
13
14export 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.

App.jsx
1import { useEffect, useState } from "react"
2
3function App() {
4 const [counter, setCounter] = useState(0)
5
6 useEffect(() => {
7 let interval
8
9 const updateCounter = () => {
10 setCounter(currentValue => currentValue + 1)
11 }
12
13 interval = setInterval(() => {
14 updateCounter()
15 }, 1000)
16
17 return () => {
18 // Clear the interval when component is unmounted
19 clearInterval(interval)
20 }
21 }, [])
22
23 return (
24 <div className="App">
25 <div>Count is {counter}</div>
26 </div>
27 )
28}
29
30export 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!

Leave a Comment

© 2024 CodingDeft.Com