Skip to content

Instantly share code, notes, and snippets.

@alekhinen
Created January 16, 2020 18:40
Show Gist options
  • Save alekhinen/1a6c106b8a7d09afe1566f57c0951232 to your computer and use it in GitHub Desktop.
Save alekhinen/1a6c106b8a7d09afe1566f57c0951232 to your computer and use it in GitHub Desktop.
Covers the lifecycle hooks of a react class component.
import React from 'react';
interface OwnProps {
// add some properties.
}
interface OwnState {
// add some properties.
}
class SampleComponent extends React.Component<OwnProps, OwnState> {
// lifecycle hook when this class is first instantiated.
constructor(props: OwnProps) {
super(props);
// typically set initial internal state here.
}
// lifecycle hook after this component is mounted into the render tree.
// e.g. first render.
componentDidMount() {
// typically dispatch out to network requests here.
}
// lifecycle hook after either the props or the state changes.
componentDidUpdate(prevProps: OwnProps, prevState: OwnState) {
// could be used to re-fetch data or directly manipulate the DOM.
}
// lifecycle hook before this component is removed from the render tree
// and destroyed.
componentWillUnmount() {
// good place to remove subscriptions (websockets, setTimeouts, etc).
}
// lifecycle hook for when an error is thrown in one of the children.
componentDidCatch(error: Error) {
// e.g. could be used for logging or graceful handling of a known error.
}
// function to determine if this component should re-render
shouldComponentUpdate(nextProps: OwnProps, nextState: OwnState): boolean {
// this should rarely be used – and only if you know what you are doing.
// by default, a re-render will always trigger if state or props change.
// in comparison, a `PureComponent` will only re-render if a shallow comparison fails.
return true;
}
}
export default SampleComponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment