Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
63 lines (47 sloc) 2.44 KB

React.lazy

React.lazy currently lets us render a dynamic import as a regular component. The signature of React.lazy tells us that it takes an async function which resolves to a module export, which in turn contains a default field:

declare export function lazy<P>(
  component: () => Promise<{ default: React$ComponentType<P>, ... }>
): React$ComponentType<P>

Here's how we may annotate a React.lazy loaded funcitonal component:

//@flow
const React = require('react')

type Props = {| cornStyle: 'spiraling' | 'colorful' |}

function Unicorn(x: Props) {
  return null
}

const LazyFunctionComponent = React.lazy(() =>
  Promise.resolve({ default: Unicorn })
)

const lazy_unicorn_ok = () => <LazyUnicorn cornStyle="spiraling" /> // ok
const lazy_unicorn_error = () => <LazyUnicorn corn="spiraling" /> // error

We can pass the returns of React.forwardRef to React.lazy:

const { useImperativeHandle } = React

function Demo(props, ref) {
  useImperativeHandle(ref, () => ({
    moo(x: string) {},
  }))
  return null
}

const Lazy = React.lazy(async () => ({
  default: React.forwardRef(Demo),
}))

function App() {
  // Error below: moo expects a string, given a number
  return (
    <React.Suspense fallback="Loading...">
      <Lazy ref={ref => ref && ref.moo(0)} />;
    </React.Suspense>
  )
}

References

You can’t perform that action at this time.