Skip to content

Latest commit

 

History

History
182 lines (104 loc) · 2.71 KB

react-intro-lifecycles.md

File metadata and controls

182 lines (104 loc) · 2.71 KB
marp theme
true
ctheme

width:600px


Functional components

function Welcome(props) {
  return <h1>Hello, {this.props.name}</h1>;
}

Class components

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Class components

The only method you must define in a React.Component subclass is called render(). All the other methods are optional.


Class components

class Header extends React.Component {
  constructor(props) {
    super(props);
    // this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    // return {favoritecolor: props.favcol };
  }
  componentDidMount() {
    // this.setState({favoritecolor: "yellow"})
  }
  shouldComponentUpdate(nextProps, nextState) {
    // return nextState.favoritecolor !== this.state.favoritecolor;
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    //
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
    // if (this.props.userID !== prevProps.userID) {
    //   this.fetchData(this.props.userID);
    // }
  }
  componentWillUnmount() {
    // alert("The component named Header is about to be unmounted.");
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

Component lifecycle

Mount phase:

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

Component lifecycle

Update phase:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

Component lifecycle

Unmount phase:

  • componentWillUnmount()

Component lifecycle

Error handling

  • static getDerivedStateFromError()
  • componentDidCatch()

Component lifecycle

width:1000


alt


Functional lifecycle

width:650


Resources

<style scoped>ul li { font-size: 0.8rem; }</style>