DEV Community

Cover image for React Custom Hook: useTimeout
Sergey Leschev
Sergey Leschev

Posted on

React Custom Hook: useTimeout

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useTimeout" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.


import { useCallback, useEffect, useRef } from "react"

export default function useTimeout(callback, delay) {
    const callbackRef = useRef(callback)
    const timeoutRef = useRef()
    useEffect(() => {
        callbackRef.current = callback
    }, [callback])
    const set = useCallback(() => {
        timeoutRef.current = setTimeout(() => callbackRef.current(), delay)
    }, [delay])
    const clear = useCallback(() => {
        timeoutRef.current && clearTimeout(timeoutRef.current)
    }, [])
    useEffect(() => {
        return clear
    }, [delay, set, clear])
    const reset = useCallback(() => {
    }, [clear, set])
    return { reset, clear }
Enter fullscreen mode Exit fullscreen mode

The "useTimeout" hook encapsulates the logic for setting, clearing, and resetting timeouts within a React component. It takes two parameters: a callback function and a delay duration in milliseconds. Whenever the specified delay elapses, the provided callback function is executed.

One of the significant advantages of this custom hook is that it ensures the callback function remains up to date even if it changes during component re-renders. By using a useRef to store the callback reference, the hook guarantees that the latest version of the function is always called.

Moreover, the "useTimeout" hook optimizes performance by utilizing useCallback to memoize the "set" and "clear" functions. This means that the functions are only recreated when their dependencies change, preventing unnecessary renders and enhancing efficiency.

import { useState } from "react"
import useTimeout from "./useTimeout"

export default function TimeoutComponent() {
    const [count, setCount] = useState(10)
    const { clear, reset } = useTimeout(() => setCount(0), 1000)
    return (
            <button onClick={() => setCount(c => c + 1)}>Increment</button>
            <button onClick={clear}>Clear Timeout</button>
            <button onClick={reset}>Reset Timeout</button>
Enter fullscreen mode Exit fullscreen mode

The "useTimeout" hook can be utilized in various scenarios where timed actions are required. For example, in a countdown component like the "TimeoutComponent" showcased above, you can easily implement a timer that resets after a specific duration. By using the "useTimeout" hook, you can effortlessly update the countdown value and manage the timeout without worrying about complex timeout management code.

Full Version | React Custom Hooks:

Top comments (0)