10

Say I have a setup that looks like this:

function App() {
  return (
    <React.Suspense fallback={<SomeOtherComponent />}>
      <SomeComponent />
    </React.Suspense>
  );
}

Is there an easy way during development that I can trigger <SomeComponent /> to suspend for a set period of time so that I can see what the fallback state looks like?

I want this as I am trying to ensure that my fallback state both looks correct and that the transition to the non-fallback state does not look janky. I am hoping that there is a solution that can make the component suspend programmatically on the Javascript side.

Jack Gore
  • 3,874
  • 1
  • 23
  • 32
  • Does this answer your question? [React suspense/lazy delay?](https://stackoverflow.com/questions/54158994/react-suspense-lazy-delay) – Luke Willis Jan 07 '21 at 00:13
  • 1
    I don't know if there is a built in way to show the fallback on command, but if you throw a promise from inside a suspense you will receive the fallback until the promise completes. You might be able to set something up using this to do what you want. – Jacob Smit Jan 07 '21 at 00:17

1 Answers1

7

Vanilla Solution (not recommended)

The unofficial way of triggering a suspense is by throwing a promise.


const SuspenseTrigger = () => {
  throw new Promise(() => {})
}

Note, future versions of react may not support this method of triggering a suspense. Please don't use in production, see this answer for more on why its not a good idea.

Example Implementation:


const SomeComponent = () => {
  const [ready, setReady] = useState(false)

  useEffect(() => {
    setTimeout(() => setReady(true), 1000)
  }, [])

  return ready 
    ? <div>hello world!</div>
    : <SuspenseTrigger/>
}

const App = () => 
  <Suspense fallback={<div>loading</div>}>
    <SomeComponent/>
  </Suspense>
chantey
  • 4,252
  • 1
  • 35
  • 40
  • I'm new to all of this React stuff, is there any way to make this succeed after some time?.. I removed the useEffect wrapper around the setTimeout, and this actually makes the component keep being rerendered. Idk if this is good or bad... however, I am now able to set a variable to true after some time and render the components inside suspense... – ii iml0sto1 Sep 22 '22 at 11:26
  • I'd highly reccomend not playing with suspense triggers if you're new. Check out a library like [recoil](https://recoiljs.org/docs/guides/asynchronous-data-queries/) which does this properly. Also, yes useEffect is super important, otherwise infinite loop, further reading [here](https://reactjs.org/docs/hooks-effect.html). – chantey Sep 23 '22 at 00:04
  • 1
    i made another sample, and im supposed to check it out due to my work :) – ii iml0sto1 Sep 23 '22 at 06:02