We’ve used component lifecycle methods before, but we haven’t really talked about what they are or how they work. You can kind of think of them as callbacks that react uses to tell you about the different phases that your component goes through before it’s rendered to the page.

There are three distinct operations that your component can go through. It can be either mounting, updating, or unmounting. So, when your component is mounting, being rendered into the page for the first time, when it’s updating, something changes it needs to update what it’s being. And when it’s unmounting, it means that it’s leaving your page.

Each of these operations happens for three different phases. You have the render phases, your render function gets everything here is supposed to be pure, immutable and so on. Then you have the pre-commit phase, which is where you can interact with the dom and read from it. But, you can’t write. And then you have the final commit phase. After this one, you can interact with the dom, play with it and change it and all of that.

You first have the constructor. This is where your component gets constructed. Then you have get derived state from props. This is the new one from react 16.3. And the render function goes through both mounting and updating. In the commit phase, writes your stuff to the dom. Did mount if you are currently mounting, or did update if you are updating. Whereas in unmount … Unmount. Right here in the update phase, you also have should component update. When your component is mounting, it first calls your constructor setting up the component for the first time. Then you get your get draft state from props. Your last chance to update the state based on prop changes. Then your component renders. React writes it to the dom. Your lifecycle mattered for did component mount. If you’re updating, that means your state has changed, or your props have changed. You again get the chance to call get draft state from props. Then should component update is called. And your render function gets called, then your react is rendering you to the dom and in the end, did update where you can do whatever you need to do after a component update.

I borrowed this chart from Dan Abermoth, so you know it’s correct. But what I really wanted to say about component lifecycle methods is that they’re one of those things that seems really important, but in practice you actually don’t get to use it that much. Most often, really, you will just use component did mounts to maybe start like a data load or something. But honestly, other than declarative animation and calling APIs from your components, I haven’t really found that much use from component lifecycle methods.


Know someone who wants to learn React and its whole ecosystem? Share 👇