The cleanup function in useEffect runs before the component unmounts. This allows for proper cleanup of resources and prevents memory leaks.