Skip to content

Commit 463c62e

Browse files
authored
fix: switch to getDerivedStateFromError to avoid unnecessary rerender (#67)
Closes #66
1 parent cd9415f commit 463c62e

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

src/index.js

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ const changedArray = (a = [], b = []) =>
55

66
const initialState = {error: null, info: null}
77
class ErrorBoundary extends React.Component {
8+
static getDerivedStateFromError(error) {
9+
return {error}
10+
}
11+
812
state = initialState
913
resetErrorBoundary = (...args) => {
1014
this.props.onReset?.(...args)
@@ -13,13 +17,17 @@ class ErrorBoundary extends React.Component {
1317

1418
componentDidCatch(error, info) {
1519
this.props.onError?.(error, info?.componentStack)
16-
this.setState({error, info})
20+
this.setState({info})
1721
}
1822

1923
componentDidUpdate(prevProps) {
20-
const {error} = this.state
24+
const {error, info} = this.state
2125
const {resetKeys} = this.props
22-
if (error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
26+
if (
27+
error !== null &&
28+
info !== null &&
29+
changedArray(prevProps.resetKeys, resetKeys)
30+
) {
2331
this.props.onResetKeysChange?.(prevProps.resetKeys, resetKeys)
2432
this.setState(initialState)
2533
}
@@ -30,6 +38,15 @@ class ErrorBoundary extends React.Component {
3038
const {fallbackRender, FallbackComponent, fallback} = this.props
3139

3240
if (error !== null) {
41+
// we'll get a re-render with the error state in getDerivedStateFromError
42+
// but we don't have the info yet, so just render null
43+
// note that this won't be committed to the DOM thanks to our componentDidCatch
44+
// so the user won't see a flash of nothing, so this works fine.
45+
// the benefit of doing things this way rather than just putting both the
46+
// error and info setState within componentDidCatch is we avoid re-rendering
47+
// busted stuff: https://github.com/bvaughn/react-error-boundary/issues/66
48+
if (!info) return null
49+
3350
const props = {
3451
componentStack: info?.componentStack,
3552
error,

0 commit comments

Comments
 (0)