How to implement React.js - arthur791004/notes GitHub Wiki

DOM

  • Every html document is built from elements that are called “dom elements”
  • html, div, h1 are all dom elements

DOM Tree

  • represent the html document to a tree of objects

Browser APIs

// document
document.createElement

// element
element.innerHTML
element.addEventListener
element.setAttribute

// node
node.appendChild
node.hasChildNodes
node.removeChild
node.lastChild

React

const React = {
  /**
   * @param {Function | Class | ElementName} elem
   * @param {Object} props
   * @param {Array<ElementObject | string>} children
   *
   * @return $elem 
   */
  createElement,
  
  /**
   * @description class component
   */
  Component,
}

React.Component

class Component {
  constructor(props) {
    this.props = props;
  }

  setState(state) {
    this.state = Object.assign({}, this.state, state);

    /**
     * @description this mechanism is called `Reconciliation`
     */
    reRender();
  }
}

ReactDOM

const ReactDOM = {
  render: ($elem, $rootElem) => {
    $rootElem.appendChild($elem);
  }
}

How to handle re-render

  • naive
    • delete the entire dom on every setState call and will render it again
  • cached
    • Hold a cache of the instantiated classes
    • When handling a class. In case of a match, return the cached instance
    • Instead of calling render straight away return an object with a special flag that marks it as a react class.
    • When appending a child node. If it’s a react class call its render
  • better
    • Call render on the js tree model
    • Read the current dom
    • Figure out the changes
    • Apply only these changes on the dom
  • virtual dom
    • Create a new virtual dom
    • Figure out the difference between it and the current virtual dom (diffing between two js trees can be done pretty fast)
    • Apply only these changes on the real dom
  • Fiber

Notes

  • presentation
/**
 * $elem: elementObject
 * elem: elementName
 */
const $elem = document.createElement(elem);

Reference