The useInterval Hook

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:

  1. First, import the useState and useInterval Hooks:
import React, { useState } from 'react'
import { useInterval } from 'react-hookedup'
  1. Then, we define our component and a State Hook:
export default function UseInterval () {
const [ count, setCount ] = useState(0)
  1. 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)
  1. 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.

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

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