DEV Community

Developer Ruhul
Developer Ruhul

Posted on

React-Loadable in React HOOKS

What if react-loadable was written in hooks(new featuer in react 16.7)'?

Here's a HOC written in hooks to load reactjs component asynchronously

import React, { useEffect, useState } from "react";
import nprogress from "nprogress";
import "nprogress/nprogress.css";

export default (loader, loading) => props => {
  const [loadedComponent, setComponent] = useState(null);

  // this works like componentwillMount
  if (!nprogress.isStarted()) nprogress.start();

  if (loadedComponent) nprogress.done();

  useEffect(() => {
    let mounted = true;

    mounted &&
      loader().then(
        ({ default: C }) => mounted && setComponent(<C {...props} />)
      );

    // componentUnMount
    return () => (mounted = false);
  }, []);

  // return the loaded component
  const Component = loadedComponent || loading || <div>loading..</div>;
  return Component;
};

Top comments (1)

Collapse
 
allexon profile image
Alexon da Silva Moreira

Hello, I found this cool way to load the components, would have some example where I could go down to see a working solution! - allexon@gmail.com