I was reading a doc about Error boundaries. In that how did static getDerivedStateFromError() lifecycle update the state of hasError without setState?
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
It is just a React internals.
React is responsible for the execution of lifecycle methods (as well as render). If so, React can wrap such methods into try/catch to handle errors by the execution of the getDerivedStateFromError method and consequent setState.
static nature of this method is needed to exclude the possibility of any side-effects on component.