That's not to say hooks aren't without a downside, it is more to learn, with a different mental model, and their own edge cases. But having used hooks exclusively for a larger project, I couldn't imagine going back to lifecycle methods.
That's not to say hooks aren't without a downside, it is more to learn, with a different mental model, and their own edge cases. But having used hooks exclusively for a larger project, I couldn't imagine going back to lifecycle methods.
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.