Lifecycle Method Examples

componentWillUnmount

Example

const NUM_BOXES = 32;
class Boxes extends Component {
  constructor(props) {
    super(props);
    const boxes = Array(NUM_BOXES).fill()
      .map(this.getRandomColor, this);
    this.state = {boxes};

    this.intervalId = setInterval(() => {
      const boxes = this.state.boxes.slice();
      const ind = Math.floor(Math.random()*boxes.length);
      boxes[ind] = this.getRandomColor();
      this.setState({boxes});
    }, 300);
  }
  componentWillUnmount() {
    clearInterval(this.intervalId);
  }
}

componentDidMount

AJAX Example

Hacker News API

GET https://hacker-news.firebaseio.com/v0/topstories.json

[15300069,15298833,...15267532]

GET https://hacker-news.firebaseio.com/v0/item/15300069.json

{"by":"maguay",
 "id":15300069,
 "title":"Google signs agreement with HTC",
 "url":"https://www.blog.google/topics/hardware/google-signs-agreement-htc-continuing-our-big-bet-hardware/"
}

Your

Turn

Component Lifecycle Method Examples

By Elie Schoppik

Component Lifecycle Method Examples

  • 1,992