4 ms·
The class example is misleading in terms of the line of code. The first example would have the componentDidMount and componentDidUpdate to call the same functio
by daok 7y ago
The class example is misleading in terms of the line of code. The first example would have the componentDidMount and componentDidUpdate to call the same function
componentDidMount() {
const newData = getDataWithinRange(this.props.dateRange)
this.setState({data: newData})
}
componentDidUpdate(prevProps) {
if (prevProps.dateRange != this.props.dateRange) {
const newData = getDataWithinRange(this.props.dateRange)
this.setState({data: newData})
}
}
Could be:
componentDidMount() {
get(this.props.dateRange);
}
componentDidUpdate(prevProps) {
if (prevProps.dateRange != this.props.dateRange) {
get(this.props.dateRange);
}
}
get(dateRange){
const newData = getDataWithinRange(dateRange)
this.setState({data: newData})
}
It removes the duplication.
- TheTrotters 7y agoThe original example has 10 LOC, yours has 12.
- crtlaltdel 7y agoAnd the 12 LOC example allows you to change the logic in one place and not two. While more verbose, this does make it harder to introduce bugs by forgetting to update the logic everywhere it is used (copy/pasted)
- stickfigure 7y agoYes, it's a better pattern, but then the hookophobes would complain that the example artificially inflates the line count by adding a not-strictly-necessary function. I don't think the author is being disingenuous, just trying to keep the examples straightforward. It doesn't matter anyway. With or without the function, the class example compares unfavorably to the hooks example.
- daok 7y agoThe hook functions need the knowledge that the mount and update are doing the same thing. However, the example would be more complete if the mount was doing something different. In that case, not only the class example would be more clear to read with explicit function for mount and update but also would be similar in terms of the line of code. With Hooks, if you want something different you need to do a "trick" which is less obvious than defining `componentDidMount`. I am not against Hooks, but I do not believe the example portrait the situation properly.
- wolco 7y agoPut everything in a single line then.
- towndrunk 7y agoAh... the line counter... must be better because there are fewer lines. I think I have maintained some code you have written. ;)
- ratww 7y agoThe grandparent literally starts complaining about line count... the person you're replying to is just pointing a strange mistake.
- epidemian 7y agoGods, I have no idea why you're being downvoted. The comment you're replying to literally starts with: > The class example is misleading in terms of the line of code.