React: Fragment, Lazy & Error Boundary

Going over the advance section of React documentation: React fragment, React lazy & Error Boundary

React Fragment

Fragments let you group a list of children without adding extra nodes to the DOM. The short syntax of grouping elements in a virtual HTML element:

const App = ()=>{
    return <>
        <h1>Hi</h1>
        <h2>To me</h2>
    </>
}

But in this syntax it is not possible to add attribute. To do so we will need to use the longer version.

const App = ()=>{
    const someArr = ['a','b','c']
    return <>
        {someArr.map(k=> <React.Fragment key={k}>{k}</React.Fragment>)}
    </>
}

I didn’t fine any other usage than the key.

Rect.lazy

Render a dynamic import as a regular component.

Replace...
import InnerComp = import('./components/InnerComp');
With...
const InnerComp = React.lazy(() => import('./components/InnerComp'));

But since we replace import with async call, we need to add a suspense until the async will resolve.

const App = ()=>{
    return <React.Suspense fallback={<div>Loading...</div>}>
        <InnerComp  val="Valid Hi" />
    </React.Suspense>
}

Error Boundary

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI

(Nope, unfortunately there is no hook for this one)

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(error) {
        return { hasError: true };
    }

    componentDidCatch(error, errorInfo) {
        console.log(error, errorInfo);
    }

    render() {
        if (this.state.hasError) {
            return <h1>Something went wrong.</h1>;
        }

        return this.props.children;
    }
}

Usage inside JSX:

const App = () => {
    return <ErrorBoundary>      
        <InnerComp val="Valid Hi" />
    </ErrorBoundary>
}

 It is worse to leave corrupted UI in place than to completely remove it