useTimeout Hook

The useTimeout Hook can be used just like setTimeout. We are now going to implement a component that triggers after 10 seconds have passed:

  1. First, import the useState and useTimeout Hooks:
import React, { useState } from 'react'
import { useTimeout } from 'react-hookedup'
  1. Then, we define our component and a State Hook:
export default function UseTimeout () {
const [ ready, setReady ] = useState(false)
  1. Next, we define the useTimeout Hook, which is going to set ready to true, after 10000 ms (10 seconds):
    useTimeout(() => setReady(true), 10000)
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.46.36