How Does React actually work ?

The basic concepts of React

  1. reconciliation
  2. virtual DOM
  3. rendering
  4. diffing algorithm

pre-knowledge

understand the difference between React components, elements and component


What is a React component ?

React component = class or a function that outputs an element tree.
React components also take props as the input


Not only can React elements describe a DOM node(HTML element), they can also describe a component instance.

Not only React call our component for us, it also manages the component instances.

Reconciliation

  • All React does is create a tree of elements
  • This is very fast, because React elements are just plain JavaScript objects
  • This is happening when we call the render() method
  • This tree of elements is kept in memory, it is the virtual DOM
  • The next thing to do is to sync the virtual DOM with the real DOM
  • During the initial render, there is no other way than to insert the full tree


👎Normally: n elements => n^3 operations (not ideal)

React: n elements => n operations

The Diffing algorithm assumptions

  1. Two elements of different types will produce different trees
  • isn't this obvious? Generally speaking not so much but in the context of a React application, this is completely fine
  1. When we have a list of child elements which often changes, we should provide an unique "key" as a prop

Diffing algorithm operations



Rendering

  • Rendering is handled by packages called renderers (React DOM, React Native, etc.)
  • React on its own is just a library that allow us to define components, elements and so on + it does the diffing part
  • Most of the actual implementation lives in the renderers
  • They begin the reconciliation process. They generate the three of elements and insert it wherever it has to be inserted


posted @ 2025-01-04 13:16  Felix_Openmind  阅读(16)  评论(0)    收藏  举报
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}