DEV Community

Jakub T. Jankiewicz
Jakub T. Jankiewicz

Posted on • Updated on

How to create React Higher-Order Component in TypeScript

I needed to make delay of rendering one component. The problem was that application was using same redux store for two different pages, and clear action (in useEffect) on one React Route was not fast enough and new Route was getting invalid data before it fetched new data from Backend.

So I decided to create delay higher order componenent.

This is the code:

import { useState, useEffect, FC } from 'react';

export function makeDelayComponent<PropsT>(timeout: number, Component: FC<PropsT>) {
  return function(props: PropsT) {
    const [render, setRender] = useState<boolean>(false);
    useEffect(() => {
      setTimeout(() => setRender(true), timeout);
    }, []);
    if (!render) {
      return null;
    }
    return <Component {...props}/>;
  };
}
Enter fullscreen mode Exit fullscreen mode

Notice that I didn't use any for props only generic type. TypeScript will figure out what is the type of the props based on types of the component you pass.

To use this component import it and wrap your component:


import { makeDelayComponent } from './makeDelayComponent';

type GreetingsT = {
   name: string;
};

const Greetings = makeDelayComponent(0, function({name}: GreetingsT) {
   return <p>Hello {name}</p>;
});

const App = () => {
   <Greetings name="React"/>
};
Enter fullscreen mode Exit fullscreen mode

And that's it. If you like this post, you can follow me on twitter at @jcubic and check my home page.

Top comments (0)