React Lifecycle Methods Flashcards
What are lifecycle methods?
Every component comes with methods that allows developers to update application state and reflect to ui before/after “key events.”
Not clicking or dragging, but events or stages in the lifecycle of a component.
What happens during mounting?
React runs the constructor where the initial state lives. as well as bind event handlers. After that React calls the render. It tells React what to put on page and React updates the DOM to match the output of the render. After that comes componentDidMount().
What is componentDidMount() ?
A method we define and React will automatically run it for us when once as the component has mounted. Good place to load any data with AJAX or set up subscriptions/timers.
Calling setState here will trigger re-render so be careful. Doesn’t mean we shouldn’t call setState as we often do but this happens after the render, not before the first render.
class ZenQuote extends Component { constructor(props) { super(props); this.state = {quote: ''} } componentDidMount() { axios.get("https://api.github.com/zen").then(response => { this.setState({ quote: response.data}); }); }
render() { return ( <div> <p>{this.state.quote}</p> </div> } } }
What is ComponentDidUpdate()?
componentDidUpdate() is called when a re-render occurs due to new props or setState. React will call it everytime the component is updated. Not called first time something is rendered. Called after in every rerender.
Good for syncing up with any databse if something changes in the application. After it’s updated we can send the data off to be saved in the database.
What is componentWillUnmount()
It’s the method called right before a component is destroyed or unmounted and basically removed from a page.
This is the place to do cleanup like invalidating timers, cancelling network request, removing event handlers directly put on DOM, cleaning up subscriptions.