DEV Community

Jakub T. Jankiewicz
Jakub T. Jankiewicz

Posted on • Edited on

1

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay