Learn React
Component Lifecycles
  1. methods that are invoked in series when a com‐ ponent is mounted or updated
  2. Mounting lifecycle consists of methods that are invoked when a component is mounted or unmounted
    • constructor(props), the constructor is where the state is initialized
    • componentWillMount(), is invoked before the DOM is rendered and can be used to initialize third-party libraries, start animations, request data, or perform any additional setup that may be required before a component is rendered
    • render()
    • componentDidMount(), is invoked just after the component has rendered, is another good place to make API requests, initialize any third-party JavaScript that requires a DOM, start background processes like inter‐ vals or timers
    • componentWillUnmount(), is invoked just before the component is unmounted, any processes started in componentDidMount or componentWillMount can be cleaned up
  3. Updating lifecycle is a series of methods that are invoked when a component’s state changes or when new properties are received from the parent, updating lifecycle kicks off every time setState is called
    • componentWillReceiveProps(nextProps), new properties have been passed to the component, is the only method where setState can be called
    • shouldComponentUpdate(nextProps, nextState), a predicate that can call off the update
    • componentWillUpdate(nextProps, nextState), invoked just before the component updates
    • componentDidUpdate(prevProps, prevState), invoked just after the update takes place, after the call to render
Higher-Order Components
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import fetch from 'isomorphic-fetch'
  4.  
  5. class PeopleList extends React.Component {
  6. constructor(props) {
  7. super(props)
  8. this.state = { data: [],
  9. loaded: true,
  10. loading: false }
  11. }
  12.  
  13. componentDidMount() {
  14. //this.setState({loading:true})
  15. fetch('https://randomuser.me/api/?results=100')
  16. .then(response => response.json())
  17. .then(obj => obj.results)
  18. .then(data => this.setState({
  19. loaded: true,
  20. loading: false, data
  21. })) }
  22.  
  23. render() {
  24. const { data, loading } = this.state
  25. return (loading) ?
  26. <div>Loading...</div> :
  27. <ol className="people-list">
  28. {data.map((person, i) => {
  29. const {first, last} = person.name
  30. return <li key={i}>{first} {last}</li>
  31. })}
  32. </ol>
  33. }
  34. }
  35.  
  36. ReactDOM.render(<PeopleList />, document.getElementById('root'));