The useInterval Hook can be used just like setInterval. We are now going to implement a small counter that counts the number of seconds since mounting the component:
- First, import the useState and useInterval Hooks:
import React, { useState } from 'react'
import { useInterval } from 'react-hookedup'
- Then, we define our component and a State Hook:
export default function UseInterval () {
const [ count, setCount ] = useState(0)
- Next, we define the useInterval Hook, which is going to increase the count by 1 every 1000 ms, which is equal to 1 second:
useInterval(() => setCount(count + 1), 1000)
- Finally, we display the current count value:
return <div>{count} seconds passed</div>
}
Alternatively, we could use an Effect Hook in combination with setInterval, instead of the useInterval Hook, as follows:
import React, { useState, useEffect } from 'react'
export default function IntervalWithEffect () {
const [ count, setCount ] = useState(0)
useEffect(() => {
const interval = setInterval(() => setCount(count + 1), 1000)
return () => clearInterval(interval)
})
return <div>{count} seconds passed</div>
}
As we can see, the useInterval Hook makes our code much more concise and easily readable.