The statements in the question are mostly correct. Currently error boundaries aren't supported in SSR, getDerivedStateFromError
and componentDidCatch
don't affect server side.
are they both catching the same type of errors? or each lifecycle will catch the different error?
They are catching same errors but at different phases. This previously was possible with componentDidCatch
alone:
static getDerivedStateFromError() {
return { hasError: true };
}
and
componentDidCatch() {
this.setState({ hasError: true });
}
do the same thing, componentDidCatch
has no chances to be supported on server side until the support for asynchronous rendering will be added to ReactDOMServer
.
should I always use both (in the same "error-catching" component possibly)?
You can use both. An example from the documentation shows that:
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
logComponentStackToMyService(info.componentStack);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
In this case responsibilities are divided between them. getDerivedStateFromError
does the only thing it is good for, i.e. updates the state if an error occurs, while componentDidCatch
provides side effects and can access this
component instance if needed.
"using componentDidCatch for error recovery is not optimal because it forces the fallback UI to always render synchronously" what's wrong with that?
New React releases are aimed at asynchronous rendering which is more efficient. As it was also mentioned in the comment, synchronous rendering is not a big concern for fallback UI because it can be considered edge case.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…