Jack Gore
Jack Gore

Reputation: 4252

Trigger React Suspense State while developing

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.

Upvotes: 16

Views: 9148

Answers (1)

chantey
chantey

Reputation: 5827

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>

Upvotes: 9

Related Questions