A high level overview of react components for quick reference. The react docs are awesome, but wanted to make an even more distilled version. May leave some things out for simplicity. Assumes your using react 16.8+
.
- React.Component() Class
- Use this in most cases.
- Deep compare of props/state
- React.PureComponent() Class
- No
shouldComponentUpdate()
lifecycle event - Shallow compare of props/state
- Use only when props/state are simple or need a potential speed boost
- No
- Functional Component
- Just a function
-
A large JS object managed by React
-
Initialize state in 2 ways
- Recommended, no constructor needed.
this.state = { toggle: true}
- ES2015 (old way)
constructor(props) { super(props); // required to use this, calls parent constructor this.state = { toggle: true }; }
- Modify state with
this.setState({ myNewProp: value });
this.setState
updates are merged into main objectthis.setState
calls may asynchronous, and batched- If referencing previous state in new state, use function
this.setState((state, props) => ({ toggle: state.value }));
Helpful: Visual lifecycle overview
constructor
- May not be needed if using alternative way to init state as mentioned above
- Don't call
this.setState
or cause other side effects here. - Bind events handlers here.
- Avoid copying props into state, it can cause bugs.
componentDidMount()
- Load external data here
- calling
this.setState
will cause extra render, but is useful when doing DOM related calcuations.
componentDidUpdate(prevProps, prevState, snapshot)
- Not called for initial render.
- Wrap network requests in if statement
componentWillUnmount()
- Clean up event listeners here.
- Don't use
this.setState
here, it won't called.
Rarely Used events
shouldComponentUpdate(nextProps, nextState)
- Prevent renders based on props/state.
- Largely for performance optimization.
static getDerivedStateFromProps(props, state)
- Allows you to return a modified state, based on props.
- Use sparingly, can cause bugs
- Called right before render method, on component init and future updates.
- May be useful for transition related events.
- Component instance not available.
getSnapshotBeforeUpdate(prevProps, prevState)
- called right before the most recently rendered output is committed to the DOM
- useful for chat like applications to handle scroll position
Useful for:
- Managing focus, text selection, or media playback.
- 3rd Party DOM libs
- Calling functions on child components
- Only class components accept refs on them, functional ones will not
Hooks, Error Handling, AntiPatterns