useInterval
Here's an example of a custom hook called useInterval
that sets up an interval timer:
import { useEffect, useRef } from 'react'
function useInterval(callback, delay) {
const savedCallback = useRef()
useEffect(() => {
savedCallback.current = callback
}, [callback])
useEffect(() => {
function tick() {
savedCallback.current()
}
if (delay !== null) {
const id = setInterval(tick, delay)
return () => clearInterval(id)
}
}, [delay])
}
export default useInterval
This custom hook takes a callback
function and a delay
in milliseconds as parameters, and returns an effect that sets up an interval timer. The callback
function is called repeatedly with the specified delay
between each call.
To use this custom hook, you would simply call it in your functional component and pass in a callback
function and a delay
:
import React, { useState } from 'react'
import useInterval from './useInterval'
function MyComponent() {
const [count, setCount] = useState(0)
useInterval(() => {
setCount(count + 1)
}, 1000)
return (
<div>
<p>Count: {count}</p>
</div>
)
}
In this example, we call the useInterval
hook with a callback
function that increments the count state variable by one, and a delay
of 1000 milliseconds (1 second). The callback
function is called repeatedly with a delay of 1 second between each call, and the count is displayed on the screen.