Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript generic class equivalent for React.memo

Is there any way to set new generic in React.memo?

For example, for class components, I can use

// set generic
class GenericClass<G extends string | number> extends PureComponent {}

// and use like this
<GenericClass<number> />

In the below scenario, I want to make type G generic.

type G = string;
const MemoComponent = memo<{ value: G; onValueChange: (newValue: G) => void }>(
  ({ value, onValueChange }) => {
    return (
      <select
        onClick={() => {
          // do calculation
          onValueChange(value);
        }}
      >
        Button
      </button>
    );
  }
);

I want to know is there any way to set generic in React.memo too? For example, like below

const MemoComponent = <G extends string | number | object>React.memo<{value: G}>(({value}) => component)

// and use like this
<MemoComponent<number> />
like image 829
Thu San Avatar asked Aug 13 '19 12:08

Thu San


People also ask

Is react memo same as pure component?

First things first: React. memo() does the same as PureComponent but it does not check for changes in state , only in props .

Does TypeScript support generic classes?

TypeScript fully supports generics as a way to introduce type-safety into components that accept arguments and return values whose type will be indeterminate until they are consumed later in your code.

What is generic class in TypeScript?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.


1 Answers

I had the same issue and solved like this.

    interface ISomeComponentWithGenericsProps<T> { value: T; } 

    function SomeComponentWithGenerics<T>(props: ISomeComponentWithGenericsProps<T>) {
      return <span>{props.value}</span>;
    }

    export default React.memo(SomeComponentWithGenerics) as typeof SomeComponentWithGenerics;

like image 190
Rafael Fontes Avatar answered Oct 12 '22 01:10

Rafael Fontes