Pro Yearly is on sale from $80 to $50! »

Understanding React

Understanding React

Ed35943d3199ea37b1b60c39615e8163?s=128

Raphael Amorim

June 08, 2018
Tweet

Transcript

  1. WRITING YOUR OWN 
 REACT RENDERER @ R A P

    H A M O R I M S
  2. WHO THE HELL IS THIS GUY?

  3. None
  4. Sim!
 Sou o moleque que chegou atrasado!

  5. None
  6. None
  7. Software Developer Engineer @godaddy JS Foundation Member @jquery Maintainer React-TV

    Raphael Amorim Previously @globocom, @petrobras 22 years old Mozillian Metido a besta
  8. None
  9. None
  10. Não tem desconto na compra do domínio!

  11. React @ R A P H A M O R

    I M S
  12. difference between components, their instances, and elements in React

  13. For example, you may declare a Button component by creating

    a class.
  14. When the program is running, you may have several instances

    of this component on screen, each with its own properties and local state.
  15. This is the traditional object oriented UI programming.

  16. And why introduce elements?

  17. In this traditional UI model, it is up to you

    take care of creating and destroying child component instances.
  18. If a Form component wants to render a Button component.

    It needs to create its instance, and manually keep it up to date with any new information.
  19. class Form extends TraditionalObjectOrientedView { render() { // Read some

    data passed to the view const { isSubmitted, buttonText } = this.attrs; if (!isSubmitted && !this.button) { // Form is not yet submitted. Create the button! this.button = new Button({ children: buttonText, color: 'blue' }); this.el.appendChild(this.button.el); } if (this.button) { // The button is visible. Update its text! this.button.attrs.children = buttonText; this.button.render(); } if (isSubmitted && this.button) { // Form was submitted. Destroy the button! this.el.removeChild(this.button.el); this.button.destroy(); } . . .
  20. Each component has to keep references to its DOM node

    and to the instances of the children components, and create, update, and destroy them when the time is right.
  21. Now let’s talk about React.

  22. In React, this is where the elements come to rescue.

  23. An element is a plain object describing a component instance

    or DOM node and its desired properties.
  24. It contains only information about the component type (for example,

    a Button), its properties (for example, its color), and any child elements inside it.
  25. An element is not an actual instance. Rather, it is

    a way to tell React: What you want to see on the screen
  26. You can’t call any methods on the element. It’s just

    an immutable description object with two fields: type: (string | Component) props: Object.*
  27. You can’t call any methods on the element. It’s just

    an immutable description object with two fields: type: (string | Component) props: Object.*
  28. When the element’s type is a string, an element represents

    a DOM node with that tag name, and props correspond to its attributes. This is what React will render. For example:
  29. { type: ‘button', props: { className: 'button button-blue', children: {

    type: 'b', children: 'OK!' } } }
  30. <button class='button button-blue'> <b> OK! </b> </button>

  31. By convention, when we want to create an element tree,

    we specify one or more child elements as the children prop of their containing element.
  32. What’s important is that both child and parent elements are

    just descriptions and not actual instances
  33. They don’t refer to anything on the screen when you

    create them. You can create them and throw them away, and it won’t matter much. really… React-DOM, React-Hardware, React-Native, React-TV […] does it.
  34. React Elements are easy to traverse, don’t need to be

    parsed, and of course are much lighter than the actual DOM elements.
  35. they’re just objects!

  36. However, the type of an element can also be a

    function or class corresponding to a React component.
  37. { type: Button, props: { color: 'blue', children: 'OK!' }

    }
  38. This is the core idea of React.

  39. An element describing a component is also an element, just

    like an element describing the DOM node. They can be nested and mixed with each other.
  40. This feature lets you define a OkButton component as a

    Button with a specific color property value. Without worrying about whether Button renders to a button, a div, or something else entirely.
  41. const ConfirmButton = ({ children }) => ({ type: Button,

    props: { color: ‘green', children: children } });
  42. const CreateAccount = () => ({ type: 'div', props: {

    children: [{ type: 'p', props: { children: ‘Welcome to Nubank!’ } }, { type: ConfirmButton, props: { children: ‘Yahooo!' } }, { type: Button, props: { color: 'red', children: 'Cancel' } }] });
  43. const CreateAccount = () => ( <div> <p>Welcome to Nubank</p>

    <ConfirmButton>Yahooo!</ConfirmButton> <Button color='blue'>Cancel</Button> </div> );
  44. When React sees an element with a function or class

    type, it will know to ask that component what element it renders to with the given props.
  45. { type: Button, props: { color: 'blue', children: 'OK!' }

    }
  46. React will ask Button what it renders to, and it

    will get:
  47. { type: 'button', props: { className: 'button button-blue', children: {

    type: 'b', children: 'OK!' } } }
  48. React will repeat this process until it knows the underlying

    DOM tag elements for every component on the page.
  49. const Form = ({ isSubmitted, buttonText }) => { if

    (isSubmitted) { // Form submitted! Return a message element. return { type: Message, props: { text: 'Success!' } }; } // Form still visible! Return a button element. return { type: Button, props: { children: buttonText, color: 'blue' } }; };
  50. The returned element tree can contain both elements describing DOM

    nodes, and elements describing other components. This lets you compose independent parts of UI without relying on their internal DOM structure.
  51. We let React create, update, and destroy instances.

  52. We describe them with elements we return from the components,

    and React takes care of managing the instances.
  53. In the last code, Form, Message, and Button are React

    components. They can either be written as functions, as above, or as classes descending from React.Component:
  54. class Button extends React.Component { render() { const { children,

    color } = this.props; // Return an element describing a // <button><b>{children}</b></button> return { type: 'button', props: { className: 'button button-' + color, children: { type: 'b', props: { children: children } } } }; } }
  55. When a component is defined as a class, it is

    a little more powerful than a functional component. It can store some local state and perform custom logic when the corresponding DOM node is created or destroyed.
  56. A functional component is less powerful but is simpler, and

    it acts like a class component with just a single render() method.
  57. However, whether functions or classes, fundamentally they are all components

    to React. They take the props as their input, and return the elements as their output.
  58. ReactDOM.render({ type: Form, props: { isSubmitted: false, buttonText: 'OK!' }

    }, document.getElementById('root'));
  59. At the end of this process React knows the result

    DOM tree, and a renderer like ReactDOM or React Native applies the minimal set of changes necessary to update the actual DOM nodes.
  60. Extracted from:
 
 https://medium.com/@dan_abramov/react- components-elements-and-instances-90800811f8ca

  61. Reconciliation @ R A P H A M O R

    I M S
  62. React provides a declarative API so that you don’t have

    to worry about exactly what changes on every update.
  63. Tl;dr;
 
 React’s “diffing” algorithm so that component updates are

    predictable while being fast enough for high- performance apps.
  64. render()

  65. Based on current props and initialState.

  66. Create a tree of React elements.

  67. Render is based on number of elements in the tree.

    O(n3)
  68. displaying 1000 elements === one billion comparisons

  69. React implements a heuristic O(n) algorithm based on two assumptions:

  70. 1.Two elements of different types will produce different trees.

  71. 2. The developer can hint at which child elements may

    be stable across different renders with a key prop.
  72. Elements Of Different Types

  73. Going from <a> to <img>, or from <Article> to <Comment>,

    or from <Button> to <div> - any of those will lead to a full rebuild.
  74. When tearing down a tree, old DOM nodes are destroyed.

  75. Component instances receive componentWillUnmount(). When building up a new tree,

    new DOM nodes are inserted into the DOM. Component instances receive componentWillMount() and then componentDidMount(). Any state associated with the old tree is lost.
  76. Component instances receive componentWillUnmount(). When building up a new tree,

    new DOM nodes are inserted into the DOM. Component instances receive componentWillMount() and then componentDidMount(). Any state associated with the old tree is lost.
  77. <div> <Counter /> </div> <span> <Counter /> </span>

  78. DOM Elements Of The Same Type

  79. React looks at the attributes of both, keeps the same

    underlying DOM node, and only updates the changed attributes
  80. <div style={{color: 'red', fontWeight: 'bold'}} /> <div style={{color: 'green', fontWeight:

    'bold'}} />
  81. Recursing On Children

  82. By default, when recursing on the children of a DOM

    node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference.
  83. <ul> <li>first</li> <li>second</li> </ul> <ul> <li>first</li> <li>second</li> <li>third</li> </ul>

  84. If you implement it naively, inserting an element at the

    beginning has worse performance.
  85. <ul> <li>Neymar</li> <li>Firmino</li> </ul> <ul> <li>Jesus</li> <li>Neymar</li> <li>Firmino</li> </ul>

  86. React will mutate every child.

  87. Keys

  88. In order to solve this issue, React supports a key

    attribute.
  89. When children have keys, React uses the key to match

    children in the original tree with children in the subsequent tree.
  90. <ul> <li key=“10">Neymar</li> <li key="20">Firmino</li> </ul> <ul> <li key="9">Jesus</li> <li

    key="10">Neymar</li> <li key="20">Firmino</li> </ul>
  91. Now React knows that the element with key '9' is

    the new one, and the elements with the keys '10' and '20' have just moved.
  92. https://reactjs.org/redirect-to-codepen/ reconciliation/index-used-as-key

  93. Tradeoffs

  94. Keys should be stable, predictable, and unique. Unstable keys (like

    those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated.
  95. The algorithm will not try to match subtrees of different

    component types.
  96. React-Reconciler @ R A P H A M O R

    I M S
  97. None
  98. React provides a declarative API so that you don’t have

    to worry about exactly what changes on every update.
  99. I would like to announce something that I’m working on!

  100. github.com/raphamorim/ react-ape

  101. None
  102. github.com/raphamorim/
 react-dog-renderer @raphamorims

  103. O correto é bixxxxxcoito. Thanks everybody. @raphamorims