Objective

The objective of a React developer seems to be avoiding unnecessary render cycles of components. This prevents the DOM from being updated and the application from becoming “slower”.

Analysis Tools

With the React Profiler, it can be checked which components are rendered. Otherwise, MillionJS can also be used to improve React applications.

Optimization Approaches

Approach 1

  • Using the memo() Hook ensures that the component is only rendered if the props values differ from the original ones.
  • Children components will not be re-rendered either; therefore, be cautious when using it.

Approach 2

  • A state (useState) should always be associated with a component (exception: Counter)
function App() {
  const [chosenCount, setChosenCount] = useState(0);
  function handleSetCount(newCount) {
    setChosenCount(newCount);
  }
  return (
    <>
      <Header />
      <main>
        <ConfigureCounter onSet={handleSetCount} />
        <Counter initialCount={chosenCount} />
        <Counter initialCount={0} />
      </main>
    </>
  );
}

export default App;

Explanation of State Scheduling & Batching

  • Be cautious when using a state in a function
function App() {
  log('<App /> rendered');
  const [chosenCount, setChosenCount] = useState(0);
  function handleSetCount(newCount) {
    setChosenCount(newCount);
    console.log(chosenCount);// old state
  }
  return (
    <>
      <Header />
      <main>
        <ConfigureCounter onSet={handleSetCount} />
        <Counter key={chosenCount} initialCount={chosenCount} />
        <Counter initialCount={0} />
      </main>
    </>
  );
}