Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does StaticComponent re-render even though it has no changing state?

I’m trying to understand the fundamentals of how React re-renders components on state change.

In the example below, the console.log('hi') statement in StaticComponent runs each time I trigger the onChange handler on the input element. I’m confused about why StaticComponent re-renders each time I update state. It doesn’t get any props related to the changing state, so why does the log statement run each time? React dev tools also shows the component re-rendering each change with the "highlight" feature.

Is this normal react behavior? Feels like it violates most of what I’ve read about react so far, and it being economical by only updating what needs to be.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { useState } from 'react';

const DisplayComponent = ({ text }) => {
  return <p>{text}</p>
}

const StaticComponent = () => {
  console.log('hi')
  return <p>text</p>
}

export default function Home() {
  const [displayText, setDisplayText] = useState()
  return (
    <>
      <DisplayComponent text={displayText} />
      <StaticComponent />
      <input onChange={(event) => setDisplayText(() => event.target.value)} type="text" value={displayText}/>
    </>
  );
}

>Solution :

Unfortunately, it’s a normal react behavior. However, it would just rerender the virtual DOM but not the actual DOM.

If you still want to prevent that. The memo is what you need.

import { useState, memo } from 'react';

const DisplayComponent = ({ text }) => {
  return <p>{text}</p>
}

const StaticComponent = memo(() => {
  console.log('hi')
  return <p>text</p>
})

export default function Home() {
  const [displayText, setDisplayText] = useState()
  return (
    <>
      <DisplayComponent text={displayText} />
      <StaticComponent />
      <input onChange={(event) => setDisplayText(() => event.target.value)} type="text" value={displayText}/>
    </>
  );
}

For more infomation
https://beta.reactjs.org/reference/react/memo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading