|
|
|
|
|
by judofyr
2381 days ago
|
|
All of these discussions seems to forget that React hooks is two different things combined: (1) it's a new magic way of having stateful components and (2) it's a new set of APIs. I don't quite see why they _have_ to be so coupled. Wouldn't this be possible as well? class Chart extends Component {
constructor(props) {
super(props)
this.useEffect(() => {
const newData = getDataWithinRange(dateRange)
this.setState({data: newData})
}, () => this.props.dateRange);
}
}
You're not able to completely mirror the API (e.g. here the dependencies has to be a function), but you would get code which behaves very similar without the weird hook API. I'm sure these APIs would have various gotchas in order to be used correct, but it's not like React hooks is gotcha-free at all.Interestingly, useMemo doesn't even need to be defined in React in a class-based component: function useMemo(f, dep) {
let prev;
let value;
return function() {
let next = dep();
if (next !== prev) {
prev = next;
value = f();
}
return value;
}
}
class Chart extends Component {
data = useMemo(
() => getDataWithinRange(this.props.dateRange),
() => this.props.dateRange)
)
}
This is also just one of the possible APIs. I'm sure there are variants of this which are more performant and/or easier to work with. |
|
But, the React team deliberately opted to only implement hooks for function components for a few reasons:
- Function components didn't have capability parity with class components in terms of having state and side effects
- Class components already had the ability to do this kind of functionality overall
- Long-term, function components are easier for React to deal with for things like hot reloading and the upcoming Concurrent Mode. By dangling a carrot to convince folks to move to function components + hooks, it becomes easier to implement that functionality for the React team.