Introduction to react

React is an open source JavaScript framework developed by Facebook. Key features of React are
  • JS framework for developing UI components
  • Components can be written using classes or functions
  • Uses virtual DOM concept and reconciliation resulting in better performance
  • React uses JSX
  • React can be used to create single page applications
  • In React apps, pages are rendered on client side (html is generated using JavaScript) unless prerendering is used.

Virtual DOM

Main reason why React is so popular and fast is - Virtual DOM and reconciliation process. React maintains virtual copy of DOM. Here is how virtual dom works.
  • Before any virtual DOM changes happen, React takes snapshot of current virtual DOM.
  • After changes in virtual DOM, React compares current vdom with snapshot vdom. Important thing to note here is that changes are not done directly to real DOM as they are expensive. After comparison using diffing algorithm, react knows how to synch changes with real dom.
  • Then react will only render that part of UI which has changed. This process is called as reconciliation.

What is diffing algorithm

Diffing algorithm (it is a heuristic algorithm of complexity O(n) is used to find out what has changed between current and previous vdom.
  • If root elements change from one type to another, React will tear down old tree and build new.
  • If root types are same and attributes have changed, react will only update attributes. Same process will apply to all children
  • When comparing children, react uses key prop to check if element is same or different.

What are rendering types

  • Server Side - When HTML markup for web page is generated on server, it is called as server side rendering. All web apps created before 2008 were rendered on server side as JavaScript frameworks like React did not exist back then.
  • Client Side - When HTML markup for web page is generated on client, it is called as client side rendering. In react, HTML markup for app is generated on client side using JavaScript. But react also supports server side rendering using react-snapshot or react-snap
Complex problems, Simple Solutions