Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Suspense not working with useEffect/setTimeOut

I have suspense like this in the App file

<Suspense fallback={<DelayedFallback />}>

Then I have an useEffect/setTimeOut:

const DelayedFallback = () => {
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    setTimeout(() => setLoaded(true), 5000);
  }, []);

  return <> {!loaded && <Loading />} </>;
};

export default DelayedFallback;

The purpose is the client wants people who visit the website to watch their video.

Suspense is not respecting this.

Any help would be appreciated!

like image 464
Sylwia Makuch Avatar asked Jan 18 '26 07:01

Sylwia Makuch


1 Answers

If what you need is to delay the rendering of a component for an arbitrary amount of time you could simply do something like:

const [isLoaded, setIsLoaded] = useState(false);

useEffect(() => {
  setTimeout(() => {
    setIsLoaded(true);
  }, 5000);
});

if (!isLoaded) return <Loading />;

return <MyComponent />;

If you are using <video> you could use the ended event instead of a setTimeout.

At the moment, Suspense is only meant for lazy loading React components.

like image 61
Camilo Avatar answered Jan 20 '26 21:01

Camilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!