View
14
Download
0
Category
Preview:
Citation preview
React tipsfor everyone
by Mislav Mandaric, 2017-03-30
Contents
• State• Rerender• ES2016+• Composition and Higher Order Components (HOC)
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 }));
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
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
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 = () => { … }
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
Thank you! Questions?
Demo code available at
https://github.com/axilis/chch-react
Recommended