I know I should use if-else when branching UI logic. But I'm curious what happens when using a try-catch block in a functional component or render function like below? Is it the anti-pattern?
function SomeScreen() {
try {
if (foo) {
throw Error();
}
if (bar) {
throw Error();
}
return <Children />
} catch (e) {
return <ErrorComponenet error={e} />
}
}
React does not see what you are doing in the component. It just executes the body of the component and expects you to return a React Element. It is all that it cares about.
Why would you need a try-catch in the body of the component at first place? If a function might crash, that is the responsibility of the function to handle its errors, you cant always use try catch when using such a function, it is a code smell.
using a try catch in the body of the component would only prevent you from executing invalid code, like trying to access a property of something that does not exist, but still this is not the problem of the component itself to handle such scenarios, it is your problem that you are trying to do something invalid and you should fix that instead of making the component to be silent for errors.
If something is against the react rules and that leads to a crash, you can not prevent that with try-catch, because it is still a valid JS. In that case you have to use ErrorBoundaries
Example:
<div>{ {} }</div>
There is no JS error. You are calling React.createElement('div', null, {})
and there is no JS crash, you can't use try-catch. But it will lead to crash in react-dom
, since objects aren't valid elements. The only way to handle that is by ErrorBoundary