Code-splitting components with lazy()
import {lazy} from 'react'
const Chart = lazy(() => import('./Chart'))
// in the render part, use `Chart` as normal
render(){
return (
<div>
// ...
<TabContent visible={visibleTab===2}>
<Chart />
</TabContent>
</div>
)
}
Avoiding spinners with Suspense
import Spinner from './Spinner'
import {Suspense} from 'react'
return (
<Suspense fallback = { <Spinner /> }>
.....
</Suspense>
)
Suspense
and lazy
provide an easy way for concurrent rendering.
// use hook to implement concurrent rendering
import {scheduleCallback as defer} from 'scheduler'
// defer: ...
Data fetching with React Cache
import {createResource} from 'react-cache'
const apiResource = createResource(path => {
return fetchAPI(path)
})
render(){
const data = APIResource.read(`/reviews/${this.props.id}`)
return (
...
)
}
No need to manually track whether data is empty or not. Just use Suspense
.
Prerendering offscreen content
Time-slicing:
- rendering is non-blocking
- coordinate multiple updates at different priorities
- prerender content in the background with slowing down visible content
Suspense:
- Access async data from a server as easily as sync data from memory.
- Pause a component’s render without blocking siblings
- Precisely control loading states to reduce jank
lazy
,Suspense
forreact
16.6
Concurrent Mode
forreact
16.7
React Cache, Scheduler
will come soon