useTimeout documentation

The useTimeout hook is a custom React hook that allows you to execute a callback function after a specified delay.

Type

Hooks

import

import { useTimeout } from '@pillar-ui/hooks'

Table of Contents

Why useTimeout

The useTimeout hook provides a simple way to execute a callback function after a specified delay. It is useful for scenarios where you need to delay the execution of a function, such as performing an action after a certain period of time has elapsed.

Installation

To use the useTimeout hook, simply import it into your React component:

import { useTimeout } from '@pillar-ui/hooks'

Parameters

The useTimeout hook takes the following parameters:

  • callback: TimeoutHandler: The callback function to be executed after the specified delay.
  • delay: number (optional, default: 150): The delay, in milliseconds, before the callback function is executed. If not provided, a default delay of 150 milliseconds will be used.

Returned Value

The useTimeout hook does not return any value. Instead, it sets up a timer to execute the callback function after the specified delay.

Usage

To use the useTimeout hook, call it inside your functional component:

import { useTimeout } from '@pillar-ui/hooks'

function MyComponent() {
  const handleTimeout = () => {
    console.log('Timeout executed')
  }

  useTimeout(handleTimeout, 2000)

  return <div>Check the console after 2 seconds.</div>
}

In the example above, the useTimeout hook is used to execute the handleTimeout function after a delay of 2000 milliseconds (2 seconds). The message "Timeout executed" will be logged to the console after the specified delay.

Implementation details

The useTimeout hook internally uses the useEffect, useRef, and useCallback hooks from React to manage the timer. The savedCallback ref stores the latest version of the callback function. The timerRef ref stores the timer ID returned by setTimeout. The persistedCallback is a persistent version of the callback function created using the usePersistentCallback hook for stability across renders.

Error Handling

The useTimeout hook performs some basic error checking on the input parameters to ensure they are valid. It throws an error if the callback parameter is not a function, if the delay is smaller than 0, or if the delay is NaN.

Conclusion

The useTimeout hook simplifies the process of executing a callback function after a specified delay. Whether you need to perform an action after a certain period of time or add a delay to a specific behavior, this hook provides an easy-to-use solution.