Skip to content

Commit 1502ad0

Browse files
belozeryarastqt
authored andcommitted
docs: lazy modifiers
1 parent f6045a7 commit 1502ad0

File tree

1 file changed

+83
-1
lines changed

1 file changed

+83
-1
lines changed

website/docs/guides/lazy.md

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,86 @@ id: lazy
33
title: Lazy modifiers
44
---
55

6-
soon.s
6+
Solution for better code spliting with React.lazy and dynamic imports
7+
8+
## Structure
9+
10+
```
11+
src/components/Block/
12+
├── Block.tsx
13+
├── _mod
14+
│   └── Button_mod.async.tsx
15+
│   └── Button_mod.css
16+
│   └── Button_mod.tsx
17+
```
18+
19+
## Declaration
20+
21+
**Step 1.** Declare the part of the code that should be loaded dynamically.
22+
23+
```tsx
24+
// Block/_mod/Block_mod.async.tsx
25+
import React from 'react'
26+
import { cnBlock } from '../Block'
27+
28+
import './Block_mod.css'
29+
30+
export const DynamicPart: React.FC = () => <i className={cnBlock('Inner')}>Loaded dynamicly</i>
31+
32+
// defualt export needed for React.lazy
33+
export default DynamicPart
34+
```
35+
36+
**Step 2.** Declare the modifier.
37+
38+
```tsx
39+
// Block/_mod/Block_mod.tsx
40+
import React, { Suspense, lazy } from 'react'
41+
import { cnBlock } from '../Block'
42+
43+
export interface BlockModProps {
44+
mod?: boolean
45+
}
46+
47+
export const withMod = withBemMod<BlockModProps>(
48+
cnBlock(),
49+
{
50+
mod: true,
51+
},
52+
(Block) => (props) => {
53+
const DynamicPart = lazy(() => import('./Block_mod.async.tsx'))
54+
55+
return (
56+
<Suspense fallback={<div>Updating...</div>}>
57+
<Block {...props}>
58+
<DynamicPart />
59+
</Block>
60+
</Suspense>
61+
)
62+
},
63+
)
64+
```
65+
66+
> **NOTE** If your need SSR replace React.lazy method for load `Block_mod.async.tsx` module to [@loadable/components](https://www.smooth-code.com/open-source/loadable-components/) or [react-loadable](https://github.com/jamiebuilds/react-loadable)
67+
68+
## Usage
69+
70+
```ts
71+
// App.tsx
72+
import {
73+
Block as BlockPresenter,
74+
withMod
75+
} from './components/Block/desktop';
76+
77+
const Block = withMod(BlockPresenter);
78+
79+
export const App = () => {
80+
return (
81+
{/* chunk with DynamicPart not loaded */}
82+
<Block />
83+
84+
{/* chunk with DynamicPart loaded */}
85+
<Block mod />
86+
)
87+
}
88+
```

0 commit comments

Comments
 (0)