esra-justBI
6/26/2019 - 8:46 AM

React Lifecycle Methods

Lifecycle Methods: get called at certain moments in a component's life.

  1. Mounting lifecycle methods: a component mounts when it renders for the first time. It calls these three methods in order:
  • componentWillMount(){}: gets called right before render.
  • render: also belongs to updating lifecycle methods.
  • componentDidMount: gets called after the HTML from render has finished loading. If you use AJAX to fetch initial data from an API, then this is the place to make the AJAX call. It is a good place to connect a react app to external applications, such as web APIs or JS frameworks. It is also the place to set timers using setTimeout or setInterval. You use DidMount to show something that happen right after the ver yfirst rendering.
  1. Updating lifecycle methods. A component updates every time that it renders, starting with the second render.
  • componentWillReceiveProps: will be called before the rendering begins. Only gets called if the component will receive props. Will get passed one argument: an object called nextProps. This is a preview of the upcoming props object that the component is about to receive. Common use: comparing incoming props to current props/state, and deciding what to render based on that comparison.
  • shouldComponentUpdate: gets called after, but before rendering begins. Return either true (nothing happens) or false (component will not update: none other lifecycle methods will be called, including render). You should only let it return false under certain conditions. Then your component will not update. It receives two arguments: nextProps, and nextState. It it typical to compare them to the current this.props and this.state.
  • componentWillUpdate: gets called after. Received 2 arguments: nextProps, nextState. You cannot call this.setState from the body of componentWillUpdate. Main purpose: interact with things outside of the React architecture. E.g. check window size or interact with API.
  • render
  • componentDidUpdate: called after any rendered HTML has finished loading. Gets passed prevProps and prevState. References to the component's props and state before the current udpating period began. You can compare them to the current props and state. cUsually used for interacting with things outside of the React environment, like the browser or APIs.

Unmounting: when the component is removed from the DOM. This could happen if DOM is rendered without the component, or if the user navigates to a different website/closes browser.

  • componentWillUnmount: called before a component is removed from the DOM. If a component initiates any methods that require cleanup, then componentWillUnmount is where you should put that cleanup.