Skip to content
This repository has been archived by the owner on Jul 10, 2020. It is now read-only.

Latest commit

 

History

History
73 lines (59 loc) · 2.72 KB

09-react-rerender-a-react-application-bea3a0e6.md

File metadata and controls

73 lines (59 loc) · 2.72 KB

09. Rerender a React Application

Notes

  • Updating the DOM is typically the slowest part of the whole process. React only updates what’s necessary.
  • React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.
  • When we re-render the entire app with setInterval you can see the clock changes without a browser window refresh.
<body>
  <div id="root"></div>
  <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
  <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
  <script type="text/babel">
    const rootElement = document.getElementById('root');

    function tick() {
      const time = new Date().toLocaleTimeString();
      const element = `
        <div>
          <input value="${time}" />
          <input value="${time}" />
        </div>
      `;
      rootElement.innerHTML = element;
    }

    tick();
    setInterval(tick, 1000);
  </script>
</body>
  • The focus remains on the selected element because React keeps track of it. React also keeps track of the actual changes within our app so even though we call ReactDOM.render every second, it will not refresh every element inside, just the time value.
<body>
  <div id="root"></div>
  <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
  <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
  <script type="text/babel">
    const rootElement = document.getElementById('root');

    function tick() {
      const time = new Date().toLocaleTimeString();
      const element = (
        <>
          <input value={time} />
          <input value={time} />
        </>
      );
      ReactDOM.render(element, rootElement);
    }

    tick();
    setInterval(tick, 1000);
  </script>
</body>
  • Even though we create an element describing the whole UI tree on every tick, only the text node whose contents have changed gets updated by React DOM.

Additional resource