xxxxxxxxxx
import React, { useEffect } from 'react';
function YourComponent() {
useEffect(() => {
const timeoutId = setTimeout(() => {
// Code to be executed after the timeout
}, 3000); // 3000 milliseconds = 3 seconds
return () => {
clearTimeout(timeoutId); // Clearing the timeout if the component unmounts before it expires
};
}, []);
// Rest of your component code
return (
// Your JSX code
);
}
export default YourComponent;
xxxxxxxxxx
const App = () => {
useEffect(() => {
const timer = setTimeout(() => console.log("Hello, World!"), 3000);
return () => clearTimeout(timer);
}, []);
};
xxxxxxxxxx
JSX
import React from 'react';
export default function useTimeout(callback, delay) {
const timeoutRef = React.useRef(null);
const savedCallback = React.useRef(callback);
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
React.useEffect(() => {
const tick = () => savedCallback.current();
if (typeof delay === 'number') {
timeoutRef.current = window.setTimeout(tick, delay);
return () => window.clearTimeout(timeoutRef.current);
}
}, [delay]);
return timeoutRef;
};