Autoplay

    Manage React Component State with Lifecycle Methods

    Joe MaddaloneJoe Maddalone

    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.

    reactReact
    0.14 - 16
    Code

    Code

    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
    Transcript

    Transcript

    00:02 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.

    00:13 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.

    00:29 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.

    00:45 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.

    00:55 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.

    01:19 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."

    01:38 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.

    Discuss

    Discuss