React New Features

Lazy & Suspense & memo

On the way to concurrent rendering

Error Boundary

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

Error Boundary

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

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

  render() {
    const {
      hasError,
    } = this.state;

    if (hasError) return <h1>Something went wrong.</h1>;

    return this.props.children; 
  }
}
throw new Error('crash');

Error Boundary

https://codepen.io/gaearon/pen/wqvxGa?editors=0010

Lazy & Suspense

import React, {
  lazy,
  Suspense,
} from 'react';

import Loading from './Loading.jsx';

const LazyComponent = lazy(() => import('./MyComponent.jsx'));

function MainBoard() {
  return (
     <Suspense fallback={<Loading />}>
       <LazyComponent />
     </Suspense>
  );
}
  • lazy must call dynamic import => return Promise
  • Only accept module default export

Demo

memo

import React, { memo } from 'react'; 

function MyComponent(props) {
  /* render using props */
}

function areEqual(prevProps, nextProps) {
  if (prevProps === nextProps) return true;

  return false;
}

export default memo(MyComponent, areEqual);
  • comparison function is inverse from shouldComponentUpdate 

memo

import React, { memo } from 'react';
import radium from 'radium';

function MyComponent(props) {}

const reduxHook = connect(/* redux Hook */);

export default memo(
  reduxHook (
    radium(
      MyComponent
    )
  )
);
import React, { memo } from 'react';
import radium from 'radium';

function MyComponent(props) {}

const reduxHook = connect(/* redux Hook */);

export default reduxHook (
  radium (
    memo (
      MyComponent
    )
  )
);

context

const MyContext = React.createContext('ContextChannel');

class MyClass extends React.Component {
  static contextType = MyContext;
  
  componentDidMount() {
    console.log(this.context);
  }

  render() {
    console.log(this.context);
  }
}

context

When using static contextType with radium module

React New Features

By Travor Lee

React New Features

  • 146