React tips

8
React tips for everyone by Mislav Mandaric, 2017-03-30

Transcript of React tips

Page 1: React tips

React tipsfor everyone

by Mislav Mandaric, 2017-03-30

Page 2: React tips

Contents

• State• Rerender• ES2016+• Composition and Higher Order Components (HOC)

Page 3: React tips

State

• Update should not be done directly• this.state.key = ‘value’;• this.setState({ key: ‘value’ });

• Updates are merged• // current state { key1: ‘value1’, key2: ‘value2’ }• this.setState({ key1: ‘new value1’, key2: this.state.key2 });• this.setState({ key1: ‘new value1’ });

• Updates can be async• this.setState({ key: [...this.state.key,

this.props.newKey] });• this.setState((prevState, props) => ({ key:

[...prevState.key, props.newKey }));

Page 4: React tips

Rerender

• Reconciliation algorithm• If node type is different, tear the whole subtree down

• DOM nodes are destroyed• Component nodes are unmounted• Create new subtree

• If node type is the same, update its data• DOM nodes attributes are updated• Component nodes props are updated• Rerender current node

Page 5: React tips

Rerender

• Rerender algorithm• Depends on shouldComponentUpdate method• If component should not be updated, whole subtree will not be

updated• Helpful constructs

• PureComponent class with immutable state

Page 6: React tips

ES2016+

• Object spread and rest operators (Stage 3)• const obj1 = { k1: 1, k2: 2 };• const obj2 = { k3: 3, k4: 4 };• const newObj = Object.assign({}, obj1, obj2, { k5: 5 });• const newObj = {...obj1, ...obj2, k5: 5 };• const { k1, k2, ...rest } = newObj;• // rest = { k3: 3, k4: 4, k5: 5 };

• Property initializer syntax (Stage 2)• this.function = this.function.bind(this);

function () { … }• this.function = () => { … }

Page 7: React tips

Composition and HOCs

• Extending components functionality without inheritance• Composition

• Special component renders generic component, with predefined props and children

• HOCs• Function accepts component and creates new one with additional

functionality• Apply this function when need to create new component

Page 8: React tips

Thank you! Questions?

Demo code available at

https://github.com/axilis/chch-react