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.
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}/>
</>
);
}
CodePudding user response:
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