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> />
First things first: React. memo() does the same as PureComponent but it does not check for changes in state , only in props .
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With