Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Manage React Component State with Lifecycle Methods

    Joe MaddaloneJoe Maddalone
    0.14 - 16

    The previous lesson introduced the React component lifecycle mounting and unmounting. In this lesson you will learn some simple uses for these hooks and how we can interact with state.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    In component willMount, we have access to our state and our prompts but we do not have access to the DOM representation of our component yet because it has not been placed into the DOM. To illustrate that, we're going to go ahead and update our state.

    I'm going to add a key of m for multiplier. I'm going to set that to two. Then in our button here, which is incrementing our state of val, I'm going to multiply that by this.state.m. We'll save that.

    We can see when we mount, our component willMount, render, and didMount have fired. When I click on this, you can see it's multiplying our val by two. We were able to set the state or intercept the state before it actually rendered.

    In component didMount, we have access to our component in the DOM. We could log out, reactDOM.findDOMNode, and we could just pass at this.

    When we mount it, we can see we've got our actual HTML element right here in the console. In component willUnmount, we have the opportunity to clean up any running processes that we might need to. Here in component didMount, I'm going to set a variable called this.inc to equal an interval and I'm going to set that for every half-second and it's just going to call this.update.

    Before I clean that up I'm going to go ahead and load it up in the browser, and when I mount it we're going to see that the Render method is being called every time we run Update. When I unmount it, because I didn't clean it up we're getting an error here that says, "We're setting state on something that isn't actually available any longer."

    To utilize component willUnmount, I'm just going to say clearInternval this.inc for increment and now, we mount. We can see our value is being incremented, that interval is being fired. When we unmount, we've cleaned that up, we get our component willUnmount, and we're done.