Bermu

REACT Advanced Features Intro 👩🏻‍🔬

2019-09-03

Code Splitting

import()


Before:

1
2
3
import {add} from './math';

console.log(add(16, 26));

After:

1
2
3
import("./math").then(math => {
console.log(math.add(16, 26));
});

when i use create-react-app or next.js , i can operate it directly. 🗳


React.lazy()


Before:

1
2
3
4
5
6
7
8
9
import OtherComponent from './OtherComponent';

function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}

After:

1
2
3
4
5
6
7
8
9
const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}

principle: when i use this .lazy api that must called import() grammar, it will return a promise as a default export containing a react component


question 💁‍♂️ : How to save components when they are not fully displayed ?
1
2
3
4
5
6
7
8
9
10
11
const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}

Yep ! that’s a Suspense brocade bag(👛) saved us.


Fragments

can be written as <></>


Context

before:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class App extends React.Component {
render() {
return <Toolbar theme="dark" />;
}
}

function Toolbar(props) {
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}

class ThemedButton extends React.Component {
render() {
return <Button theme={this.props.theme} />;
}
}

After:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const ThemeContext = React.createContext('light');

class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}

function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}

class ThemedButton extends React.Component {
static contextType = ThemeContext;
render() {
return <Button theme={this.context} />;
}
}

Forwarding refs to DOM components

1
2
3
4
5
6
7
8
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));

const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

Fancy Button get a ref to proxy button element


procedure 👨🏼‍🔧:


1.create a react ref by calling React.createRef

2.pass to <FancyButton ref={ref}>

3.React passes the (props, ref) => …function inside forwardRef as a second argument

4.forward this ref argument down to <button ref={ref}>

5.ref is attached


when i use HOC, that’s also gonna be work by React.forwardRef


Optimizing Performance

Brunch
1
yarn add --dev terser-brunch

Then: 🦉

1
brunch build -p
Browserify
1
yarn add --dev envify terser uglifyify
Rollup
1
yarn add --dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-terser

Next Lesson we clap for Hooks ! 👏🏻

Tags: react
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章