Jeff Lee
@RebootJeff
Best Practices, Gotchas, Anti-Patterns, etc
React.js Tips
Who is Jeff?
Full-Stack JavaScriptivore
@RebootJeff
React Concepts
- Composable components
- "Unidirectional" data flow
- 🌟 Declarative coding
Philosophy
- State vs Props
- Component API conventions
- "initial" props
- propTypes & defaultProps
- Component Lifecycle
- P.S. There is no "full" Virtual DOM
Details
setState
Why? Just imagine if it were synchronous instead.
Lots of diffing/updating (reconciliation) would be done with each setState call.
setState is asynchronous
updateX() {
this.setState({ x: this.state.x + 1 });
this.setState({ x: this.state.x + 1 });
}
Best Practices & Potential Guidelines
- Keep components small
- Keep `this.state` small
- Consider the difference between
GUI-related state (e.g., isOpen) versus...
data/model-related state (e.g., selectedValue) - Each `this.state` is a potential source of truth
- Consider the difference between
Component Design
⚠️ Only when absolutely necessary
(triple-check the following during PR review)...
- state
- lifecycle hooks
- refs
- DOM querying/manipulation
Best Practices & Potential Guidelines
Component Architecture
Best Practices & Anti-Patterns
setState with functions instead of objects
// broken
updateX() {
this.setState({ x: this.state.x + 1 });
this.setState({ x: this.state.x + 1 });
}
// works as intended
updateXWithFunctions() {
this.setState((prevState, props) => {
return { x: prevState.x + 1 };
});
this.setState((prevState, props) => {
return { x: prevState.x + 1 };
});
}
- this.state
- avoid direct mutation
- avoid mutation of nested objects
(use FB's solution?) - avoid tying props to state
- `key` attribute
Best Practices & Anti-Patterns
Extras
- React dev tool for Chrome
- Destructuring props & state
- Splitting up render functions
- Where to make AJAX calls?
- Backbone or React?
- Code Style/conventions
- sort component methods by type
- sort propTypes props alphabetically
- testing conventions
- Animation?
More Links
- https://camjackson.net/post/9-things-every-reactjs-beginner-should-know
- https://github.com/ryanflorence/react-training/blob/gh-pages/lessons/05-wrapping-dom-libs.md
RebootJeff
twitter.com/
github.com/
linkedin.com/in/
Find me at
RebootJeff.com
and...
Reactjs Best Practices
By rebootjeff
Reactjs Best Practices
1st draft completed: September 8, 2016
- 1,039