When a child component’s sole purpose is to consume its parent’s state, does it need to be stateful itself?
Looking at these two examples:
“Stateless”
const ServicesCard = ({ service, onClick, isPro = false }) => {
const name = isPro && service.pro?._id ? service.pro.pro_name : service.name;
let price = isPro && service.pro?._id ? service.pro.total : service.total;
// Special case scenarios
let prefix;
let suffix;
if (service.hasPages) {
prefix = 'from';
}
if (service.uid === 'abcdef') {
prefix = '';
price = `${price} per page`;
suffix = '($5 minimum)';
}
if (service.uid === 'qwerty') {
suffix = "+ gov't fees";
}
return (
<div className={styles.servicesCard} onClick={onClick}>
<h1 className={styles.header}>{name}</h1>
<p className={styles.pricing}>
<span className={styles.prefix}>{prefix}</span>
<span className={styles.price}>{`$${price}`}</span>
<span className={styles.suffix}>{suffix}</span>
</p>
</div>
);
};
Stateful
const ServicesCard = ({ service, onClick, isPro = false }) => {
const [name, setName] = useState('');
const [price, setPrice] = useState('');
const [prefix, setPrefix] = useState('');
const [suffix, setSuffix] = useState('');
useEffect(() => {
const _name = isPro && service.pro?._id ? service.pro.pro_name : service.name;
let _price = isPro && service.pro?._id ? service.pro.total : service.total;
// Special case scenarios
let _prefix;
let _suffix;
if (service.hasPages) {
_prefix = 'from';
}
if (service.uid === 'abcdef') {
_prefix = '';
_price = `${_price} per page`;
_suffix = '($5 minimum)';
}
if (service.uid === 'qwerty') {
_suffix = "+ gov't fees";
}
setName(_name)
setPrice(_price)
setPrefix(_prefix)
setSuffix(_suffix)
}, [service]);
return (
<div className={styles.servicesCard} onClick={onClick}>
<h1 className={styles.header}>{name}</h1>
<p className={styles.pricing}>
<span className={styles.prefix}>{prefix}</span>
<span className={styles.price}>{`$${price}`}</span>
<span className={styles.suffix}>{suffix}</span>
</p>
</div>
);
};
I feel like both of them would behave the same, since a re-render will be triggered by a state change higher up in the tree anyways, forcing everything to be recalculated. React also emphasizes that Data flows down.
Provided that service
is the only prop that changes, why should I use more browser memory by using the useState
& useEffect
React APIs?