0
I have a component <Filho>
who does not receive props
, but is rendered again whenever the <Pai>
has some status update (useState
).
To solve this I figured I could do, in the component <Filho>
, something like:
shouldComponentUpdate(nextProps, nextState) {
return nextState !== this.state;
}
But how to do this with Hooks? Or is there another alternative to avoid the rerender?
Current situation:
[RENDER] Pai
[RENDER] Filho
[RENDER] Pai
[RENDER] Filho
function Filho() {
// O componente Filho tem estado, apesar de eu não atualizá-lo nesse exemplo
const [b, setB] = React.useState([]);
console.log("[RENDER] Filho");
return <div></div>;
}
function Pai() {
const [a, setA] = React.useState([]);
React.useEffect(() => {
function fetchData() {
setTimeout(function(){
setA(['a', 'b']);
}, 1500);
}
fetchData();
}, []);
console.log("[RENDER] Pai");
return <Filho />;
}
ReactDOM.render( <Pai /> , document.querySelector("#app"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Expected result:
[RENDER] Pai
[RENDER] Filho
[RENDER] Pai
Good answer! The article is also good, I think the readability of the code worsens a little depending on how the method approached in the article is used, but it is good to have options in mind when facing a more serious performance problem :)
– Rafael Tavares