How to show fallback UI when errors are occurred in react functional component

80 views Asked by At
import {ErrorBoundary} from 'react-error-boundary';

export default function Home() {
  return (
    <ErrorBoundary fallback={<div>Some error occurred</div>}>
      <SomeComponent/>
    </ErrorBoundary>
  )
}

function SomeComponent(): null {
  throw new Error('error occurred')
}

The above code is not working. The error is not catched. (Fallback is not shown)

But this code below is working well.

import { useEffect } from 'react';
import {ErrorBoundary} from 'react-error-boundary';

export default function Home() {
  return (
    <ErrorBoundary fallback={<div>Some error occurred</div>}>
      <SomeComponent/>
    </ErrorBoundary>
  )
}

function SomeComponent(): null {
  useEffect(() => {
    throw new Error('error occurred')
  }, []);

  return null
}

I want to show fallback UI when a child component function throw an error.

I've searched for official documentation

0

There are 0 answers