The useTimeout Hook can be used just like setTimeout. We are now going to implement a component that triggers after 10 seconds have passed:
- First, import the useState and useTimeout Hooks:
import React, { useState } from 'react'
import { useTimeout } from 'react-hookedup'
- Then, we define our component and a State Hook:
export default function UseTimeout () {
const [ ready, setReady ] = useState(false)
- Next, we define the useTimeout Hook, which is going to set ready to true, after 10000 ms (10 seconds):
useTimeout(() => setReady(true), 10000)
- Finally, we display whether we are ready or not:
return <div>{ready ? 'ready' : 'waiting...'}</div>
}
Alternatively, we could use an Effect Hook in combination with setTimeout, instead of the useTimeout Hook, as follows:
import React, { useState, useEffect } from 'react'
export default function TimeoutWithEffect () {
const [ ready, setReady ] = useState(false)
useEffect(() => {
const timeout = setTimeout(() => setReady(true), 10000)
return () => clearTimeout(timeout)
})
return <div>{ready ? 'ready' : 'waiting...'}</div>
}
As we can see, the useTimeout Hook makes our code much more concise and easily readable.