What is the point of re-rendering the compnonets that didn't have change in their state in React?

47 Views Asked by At

I have the main component with a state and a static component inside. When the state changes, the main component is re-rendered, which makes complete sense, but the static component is re-rendered too.

import { useState } from 'react';

function StaticComponent (){
  console.log('re-rendering static component (why?)')

  return <i>Nothing non-static in here</i>
}

function App() {
  console.log('re-rendering App')
  const [state, setState] = useState(0)
  return (
    <>
      {state}<br />
      <button onClick={() => setState((state) => state + 1)}>+</button><br />
      <StaticComponent/>
    </>
  )
}

export default App

What's the point of re-rendering the static component if there is no change in props or state? I came up with a workaround by writing it the following way (and it really worked, unexpectedly for me):

{useMemo(() => <StaticComponent/>, [])}

But it's pretty obvious that this workaround is not the solution anyone would want to use. But why don't React developers implement something similar for checking if there was a state change in a specific component before re-rendering it?

1

There are 1 best solutions below

0
Adam Jenkins On BEST ANSWER

The static component is declared in the component whose state has changed. It's as simple as that.

This structure would prevent the static component from being re-rendered:

stackblitz

import { useState } from 'react';

function StaticComponent (){
  console.log('re-rendering static component (why?)')

  return <i>Nothing non-static in here</i>
}

function App({children}) {
  console.log('re-rendering App')
  const [state, setState] = useState(0)
  return (
    <>
      {state}<br />
      <button onClick={() => setState((state) => state + 1)}>+</button><br />
      {children}
    </>
  )
}

export default () => <App><StaticComponent/></App>

Important to note you should do your best to not care how many times something gets rendered, it's mostly an implementation detail and caring about it is anti-declarative (which is what makes React so simple).

Only care when you have performance issues and not before.