Introduction to Custom Hooks in React

In the React ecosystem, hooks are a powerful addition that allows developers to use state and other React features without writing a class. A custom hook is essentially a function that encapsulates reusable logic that may involve state and side effects.

What is a Custom Hook?

A custom hook is a function that starts with “use” and can call other React hooks. It’s an elegant way to reuse component logic without falling into component hierarchy.

Creating a Timeout with a Custom Hook

Imagine you want to execute a function after a specific delay. In JavaScript, you would typically use setTimeout. In React, you can create a custom hook to handle this in a way that respects the component’s lifecycle.

Here’s an example of how you might implement a custom hook for a timeout:

import { useEffect, useRef } from 'react';

function useTimeout(callback, delay) {
const savedCallback = useRef();

// Guardar la última referencia al callback
useEffect(() => {
savedCallback.current = callback;
}, [callback]);

// Establecer el timeout
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setTimeout(tick, delay);
return () => clearTimeout(id);
}
}, [delay]);
}

export default useTimeout;


How to Use the useTimeout Hook

To use this hook in your component, simply import useTimeout and pass it the function you want to execute and the delay in milliseconds.

import React from 'react';
import useTimeout from './useTimeout';

function MyComponent() {
const doSomething = () => {
console.log('¡Hice algo después de un retraso!');
};

// Usar el hook con un retraso de 5000 milisegundos (5 segundos)
useTimeout(doSomething, 5000);

return
Hola, ¡este mensaje se logueará en la consola después de 5 segundos!

;
}

export default MyComponent;

Conclusion

Custom hooks offer a modular and reusable way to incorporate state logic and side effects into your React components. With useTimeout, you can easily manage timeouts in your components in a way that is both clean and compliant with React’s lifecycle.