DEV Community

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

Posted on

4 1 1 1 1

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.

Github: https://github.com/sergeyleschev/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(() => {
        set()
        return clear
    }, [delay, set, clear])
    const reset = useCallback(() => {
        clear()
        set()
    }, [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 (
        <div>
            <div>{count}</div>
            <button onClick={() => setCount(c => c + 1)}>Increment</button>
            <button onClick={clear}>Clear Timeout</button>
            <button onClick={reset}>Reset Timeout</button>
        </div>
    )
}
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:
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4

Please leave your appreciation by commenting on this post!

It takes one minute and is worth it for your career.

Get started

Top comments (1)

Collapse
 
scriptkavi profile image
ScriptKavi β€’

Why create one when you can get all awesome hooks in a single library?

Try scriptkavi/hooks. Copy paste style and easy to integrate with its own CLI

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay