Hello again! We're back, and here to talk about our favorite subject, class components. More specifically, the lifecycle hooks. As you may remember, I previously posted about the three main phases of class, Mounting, Updating, and Un-mounting. Within each phase, there are several processes called lifecycle methods (or hooks) that help create the applications the user sees, and interact with. Well, let us get right into it!
componentDidMount: During the Mounting phase, this is invoked immediately after the initial render method. This method can be considered the original "useEffect" hook (with the empty dependency). So, componentDidMount is used for extended running procedures, like fetching data. See how functional component's, useEffect, and class component's, componentDidMount, are similar, below:
componentDidUpdate: Moving on to the Updating phase, the method componentDidUpdate is invoked right after an update occurs. It must be enclosed in a conditional statement to prevent an infinite loop (see example below). Also, notice the repetitive code in the fetch. Another reason, useEffect is more widely used.
componentWillUnmount: Lastly, at the Un-mounting phase, componentWillUnmount is invoked prior to the component getting unmounted and destroyed. Basically, the component is deleted and the page is cleared. One thing to note about this phase; Never call a setState() on this method, as nothing will be rendered. See an example below:
There are more lifecycle methods that are not used as frequently. Mounting on initial render, updating after a render, and un-mount before deleting a page are core methods that should be remembered. I hope you've gained a little more insight on how class components operate to print your ideas to paper.
Top comments (0)