To set and clear timeout in React component, you can use useEffect()
hook with empty array as second parameter. You can clear a timeout from the return function because a return function in useEffect()
runs only when the component unmounts. So the timer will run till the component is mounted.
Code Example
useEffect(() => { const timer = setTimeout(() => {} , 2000); return () => { clearTimeout(timer); }; }, []);