I define a scene: we have a component that uses parent's props and itself state.
There are two Components DC and JOKER and my step under the below:
- click DC's button
- DC setCount
- JOKER will render with the old state
- running useEffect and setCount
- JOKER does render again
I want to ask why JOKER render twice(step 3 and 5) and the first render squanders the performance. I just do not want step 3. If in class component I can use componentShouldUpdate to avoid it. But Hooks has the same something?
My code under the below, or open this website https://jsfiddle.net/stephenkingsley/sw5qnjg7/
import React, { PureComponent, useState, useEffect, } from 'react';
function JOKER(props) {
const [count, setCount] = useState(props.count);
useEffect(() => {
console.log('I am JOKER\'s useEffect--->', props.count);
setCount(props.count);
}, [props.count]);
console.log('I am JOKER\'s render-->', count);
return (
<div>
<p style={{ color: 'red' }}>JOKER: You clicked {count} times</p>
</div>
);
}
function DC() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => {
console.log('\n');
setCount(count + 1);
}}>
Click me
</button>
<JOKER count={count} />
</div>
);
}
ReactDOM.render(<DC />, document.querySelector("#app"))
setCount(props.count);
line removing that won't re-render. More on it reactjs.org/docs/hooks-effect.html – BotzowuseEffect
is set to run after the first render so that the developer gets to render something on screen before the effect runs hence increasing the user perceived performance metrics. The performance of a component is not equal to how many renders it runs. – Hollo