$30 off During Our Annual Pro Sale. View Details »

The Life and Times of a React Component

The Life and Times of a React Component

The React Component Lifecycle

Matthew Dapena-Tretter

November 18, 2014
Tweet

More Decks by Matthew Dapena-Tretter

Other Decks in Programming

Transcript

  1. THE LIFE AND TIMES OF A REACT COMPONENT The React

    Component Lifecycle
  2. HZDG.COM MATTHEWWITHANM MATTHEW DAPENA-TRETTER M@TTHEWWITHANM.COM HZDG

  3. THE VIRTUAL DOM

  4. DOM ELEMENTS? <ul class="my-list"> <li>Text Content</li> </ul>

  5. DOM ELEMENTS! align onautocompleteerror onautocomplete onwaiting onvolumechange ontoggle ontimeupdate onsuspend

    onsubmit onstalled onshow onselect onseeking onseeked onscroll onresize onreset onratechange onprogress onplaying onplay onpause onmousewheel onmouseup onmouseover onmouseout onmousemove onmouseleave onmouseenter onmousedown onloadstart onloadedmetadata onloadeddata onload onkeyup onkeypress onkeydown oninvalid oninput onfocus onerror onended onemptied ondurationchange ondrop ondragstart ondragover ondragleave ondragenter ondragend ondrag ondblclick oncuechange oncontextmenu onclose onclick onchange oncanplaythrough oncanplay oncancel onblur onabort spellcheck isContentEditable contentEditable outerText innerText accessKey hidden webkitdropzone draggable tabIndex dir translate lang title childElementCount lastElementChild firstElementChild children onwebkitfullscreenerror onwebkitfullscreenchange nextElementSibling previousElementSibling onwheel onselectstart onsearch onpaste oncut oncopy onbeforepaste onbeforecut onbeforecopy shadowRoot dataset classList className outerHTML innerHTML scrollHeight scrollWidth scrollTop scrollLeft clientHeight clientWidth clientTop clientLeft offsetParent offsetHeight offsetWidth offsetTop offsetLeft localName prefix namespaceURI id style attributes tagName parentElement textContent baseURI ownerDocument nextSibling previousSibling lastChild firstChild childNodes parentNode nodeType nodeValue nodeName click getAttribute setAttribute removeAttribute getAttributeNode setAttributeNode removeAttributeNode getElementsByTagName hasAttributes getAttributeNS setAttributeNS removeAttributeNS getElementsByTagNameNS getAttributeNodeNS setAttributeNodeNS hasAttribute hasAttributeNS matches focus blur scrollIntoView scrollIntoViewIfNeeded getElementsByClassName insertAdjacentElement insertAdjacentText insertAdjacentHTML webkitMatchesSelector createShadowRoot getDestinationInsertionPoints getClientRects getBoundingClientRect requestPointerLock animate remove webkitRequestFullScreen webkitRequestFullscreen querySelector querySelectorAll ALLOW_KEYBOARD_INPUT insertBefore replaceChild removeChild appendChild hasChildNodes cloneNode normalize isSameNode isEqualNode lookupPrefix isDefaultNamespace lookupNamespaceURI compareDocumentPosition contains ELEMENT_NODE ATTRIBUTE_NODE TEXT_NODE CDATA_SECTION_NODE ENTITY_REFERENCE_NODE ENTITY_NODE PROCESSING_INSTRUCTION_NODE COMMENT_NODE DOCUMENT_NODE DOCUMENT_TYPE_NODE DOCUMENT_FRAGMENT_NODE NOTATION_NODE DOCUMENT_POSITION_DISCONNECTED DOCUMENT_POSITION_PRECEDING DOCUMENT_POSITION_FOLLOWING DOCUMENT_POSITION_CONTAINS DOCUMENT_POSITION_CONTAINED_BY DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC addEventListener removeEventListener dispatchEvent
  6. REACT ELEMENTS <ul className="my-list"> <li>Text Content</li> </ul>

  7. JSX IS NOT HTML

  8. REACT ELEMENTS React.DOM.ul( {className: 'my-list'}, React.DOM.li( 'Text Content' ) )

  9. REACT COMPONENTS

  10. f() : ReactElement

  11. COMPONENTS React.createClass({ render: function() { return ( <a> Hello {this.props.name}

    </a> ); } });
  12. THE COMPONENT LIFECYCLE

  13. 1. MOUNTING 2. UPDATING 3. UNMOUNTING

  14. Render UNMOUNTING MOUNTING UPDATING Prop/State Changes Removal

  15. • componentWillMount() • componentDidMount() • componentWillReceiveProps() • shouldComponentUpdate() • componentWillUpdate()

    • componentDidUpdate() • componentWillUnmount()
  16. React.createClass({ render: function() { return ( <a> Hello {this.props.name} </a>

    ); }, componentWillMount: function() { } });
  17. Render UNMOUNTING MOUNTING UPDATING Prop/State Changes Removal

  18. React.render( element : ReactElement, container : DOMElement, [callback : function]

    ) : ReactComponent
  19. React.renderToString( element : ReactElement ) : string

  20. React.createClass({ render: function() { return ( <AnotherComponent /> ); }

    });
  21. • componentWillMount() • componentDidMount() • componentWillReceiveProps() • shouldComponentUpdate() • componentWillUpdate()

    • componentDidUpdate() • componentWillUnmount()
  22. • Called once per component instance • Only lifecycle method

    called on the server (React.renderToString) • Name is somewhat misleading • componentDidMount() isn’t necessarily called after • Think “constructor” componentWillMount()
  23. • Called once per component instance • Only invoked on

    client (React.render()) • First time DOM node is available (via this.getDOMNode()) • Use for interacting with browser APIs or JS frameworks • jQuery • XHR componentDidMount()
  24. Render UNMOUNTING MOUNTING UPDATING Removal Prop/State Changes

  25. element.setProps( nextProps : object, [callback : function] )

  26. element.replaceProps( nextProps : object, [callback : function] )

  27. element.setState( nextState : object, [callback : function] )

  28. <Hello name="World" /> <Hello name="Earth" />

  29. • componentWillMount() • componentDidMount() • componentWillReceiveProps() • shouldComponentUpdate() • componentWillUpdate()

    • componentDidUpdate() • componentWillUnmount()
  30. • Called when component is receiving new props • Provides

    a chance to update state in response to a prop change without triggering an extra render • Optimization over calculating state each render componentWillReceiveProps(nextProps : object)
  31. • Invoked before rendering when new props or state are

    being received • Provides a chance to cancel rendering shouldComponentUpdate(nextProps : object, nextState : object) : boolean
  32. • Invoked before DOM is updated • Provides a chance

    to store values before rendering for comparison in componendDidUpdate() • setState() can’t be used here • Probably the least-used lifecycle method componentWillUpdate(object nextProps, object nextState)
  33. • Invoked after DOM update • Useful for triggering animations

    componentDidUpdate()
  34. Render UNMOUNTING MOUNTING UPDATING Prop/State Changes Removal

  35. React.unmountComponentAtNode( container : DOMElement ) : boolean

  36. <Hello name="World" /> <SomethingElse />

  37. <Hello key="1" name="World" /> <Hello key="2" name="World" />

  38. • componentWillMount() • componentDidMount() • componentWillReceiveProps() • shouldComponentUpdate() • componentWillUpdate()

    • componentDidUpdate() • componentWillUnmount()
  39. • Invoked before component is unmounted from DOM • “cleanup”

    hook • Remove timers • Abort XHR • Cancel tweens • Remove event listeners componentWillUnmount()
  40. Render UNMOUNTING MOUNTING UPDATING Prop/State Changes Removal

  41. HZDG.COM MATTHEWWITHANM MATTHEW DAPENA-TRETTER M@TTHEWWITHANM.COM HZDG