Block Tree in Vue3

Static nodes in React are optimized for static nodes in Vue3. Static nodes in React are optimized for runtime nodes in Vue3.

const patch: PatchFn = (
  n1,
  n2,
  container,
  anchor = null,
  parentComponent = null,
  parentSuspense = null,
  isSVG = false,
  optimized = false
) = > {
  // ...
  const { type, ref, shapeFlag } = n2
  switch (type) {
    // ...
    case Static:
      if (n1 == null) {
        mountStaticNode(n2, container, anchor, isSVG)
      } else if (__DEV__) {
        patchStaticNode(n1, n2, container, isSVG)
      }
      break
  // ...
}
Copy the code

Patch is a portal that renders for different types. A Static node is mounted through a mountStaticNode. Update is required for hot updates in a development environment

const mountStaticNode = (
  n2: VNode,
  container: RendererElement,
  anchor: RendererNode | null,
  isSVG: boolean
) = > {
  // static nodes are only present when used with compiler-dom/runtime-dom
  // which guarantees presence of hostInsertStaticContent.; [n2.el, n2.anchor] = hostInsertStaticContent! ( n2.childrenas string,
    container,
    anchor,
    isSVG
  )
}

/** * Dev / HMR only */
const patchStaticNode = (
  n1: VNode,
  n2: VNode,
  container: RendererElement,
  isSVG: boolean
) = > {
  // static nodes are only patched during dev for HMR
  if(n2.children ! == n1.children) {const anchor = hostNextSibling(n1.anchor!)
    // remove existing
    removeStaticNode(n1)
    // insert new; [n2.el, n2.anchor] = hostInsertStaticContent! ( n2.childrenas string,
      container,
      anchor,
      isSVG
    )
  } else {
    n2.el = n1.el
    n2.anchor = n1.anchor
  }
}
Copy the code

React does not update static nodes.

Block Tree in React

Of course you can! We can write a Static component whose shouldComponentUpdate always returns false and skip the update of it and its children by shouldComponentUpdate

export default class Static extends React.Component {
  shouldComponentUpdate() {
    return false
  }
  
  render() {
    return this.props.children
  }
}
Copy the code

You can use it like this:

export default function App() {
  const [count, setCount] = useState(0)
  return (
    <div>
      <Static>
        <h1>Static Title</h1>
      </Static>
      <div>{count}</div>
      <button onClick={()= > setCount(count + 1)}>add one!</button>
    </div>)}Copy the code

Implement Block Tree to reduce unnecessary updates

Difference

It is not recommended to use React in this way. However, we can also see that it is very much in line with the React style 🐶

Well, the first time to write water B article, so ~