Skip to content
react

setInterval in React Components Using Hooks

Apr 29, 2022Abhishek EH2 Min Read
setInterval in React Components Using Hooks

In my previous article, I explained how to run setTimeout in React. In this article, we will see how to call setInterval in React hooks.

What is setInterval?

setInterval can be used to execute a set of code repeatedly with a fixed time delay between each call. The syntax is similar to that of setTimeout.

It accepts a callback as the first parameter, which will be called at regular intervals, and a delay as the second parameter.

setInterval can be used to show counters, refresh a scorecard at regular intervals, etc.

Example:

1setInterval(() => {
2 console.log("This message will appear after each second")
3}, 1000)

Using setInterval in React hooks

We can execute setInterval inside useEffect hook as shown below:

App.js
1import { useEffect } from "react"
2
3function App() {
4 useEffect(() => {
5 setInterval(() => {
6 console.log("This message will appear after each second")
7 }, 1000)
8 }, [])
9
10 return <div className="App"></div>
11}
12
13export default App

If you run the application and open the browser console, you will see the message gets displayed twice each time. This is because starting from React v18, in development mode, the component will mount, unmount, and then get mounted again.

Since the component is mounted again, setInterval gets called twice, hence 2 messages.

Clearing the setInterval

As we have done in the case of setTimeout, we need to clear the setInterval call when we unmount the component:

App.js
1import { useEffect } from "react"
2
3function App() {
4 useEffect(() => {
5 const intervalId = setInterval(() => {
6 console.log("This message will appear after each second")
7 }, 1000)
8 return () => {
9 clearInterval(intervalId)
10 }
11 }, [])
12
13 return <div className="App"></div>
14}
15
16export default App

Now if you run the application and check the browser console, you will see the message getting displayed only once per second.

Setting a state inside setInterval

We can increment a counter every second using setInterval as shown below:

App.js
1import { useState } from "react"
2import { useEffect } from "react"
3
4function App() {
5 const [counter, setCounter] = useState(0)
6 useEffect(() => {
7 const intervalId = setInterval(() => {
8 setCounter(oldValue => oldValue + 1)
9 }, 1000)
10 return () => {
11 clearInterval(intervalId)
12 }
13 }, [])
14
15 return <div className="App">{counter}</div>
16}
17
18export default App

If you run the code now, you will see a nice counter which increments every second.

If you have liked article, do follow me on twitter to get more real time updates!

Leave a Comment

© 2023 CodingDeft.Com