0 votes
in ReactJS by
What is the difference between try catch block and error boundaries ReactJS, Explain with example?

1 Answer

0 votes
by

Try catch block works with imperative code whereas error boundaries are meant for declarative code to render on the screen.

For example, the try catch block used for below imperative code

try {
  showButton();
} catch (error) {
  // ...
}

Whereas error boundaries wrap declarative code as below,

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

So if an error occurs in a componentDidUpdate method caused by a setState somewhere deep in the tree, it will still correctly propagate to the closest error boundary.

...