Definitelytyped: @types/react Cannot use React.memo with defaultProps

Created on 20 Jun 2019  路  9Comments  路  Source: DefinitelyTyped/DefinitelyTyped

This works

export const Foo = (props: {foo: number}) => {
  return <div>{props.foo}</div>
}
Foo.defaultProps = {foo: 1}

This doesn't

export const Foo = React.memo((props: {foo: number}) => {
  return <div>{props.foo}</div>
})
Foo.defaultProps = {foo: 1}
TS2339: Property 'defaultProps' does not exist on type 'MemoExoticComponent<(props: { foo: number; }) => Element>'.

Authors: @ferdaber @johnnyreilly @sandersn @RyanCavanaugh @tkrotoff @weswigham

Most helpful comment

Any updates on how to add a property to the result of a React.memo()? I'm currently using the "as" typecast to any, but that's hacky. Example use is where both are memoized.

All 9 comments

I believe React.memo does not actually support defaultProps, only the inner component does.

@ferdaber

export const Foo = React.memo((props: {foo: number}) => {
  return <div>{props.foo}</div>
}) as any
Foo.defaultProps = {foo: 1}
<Foo/> // render 1

Could someone explain why MemoExoticComponent cannot just extend FunctionComponent?

Memoized components aren't actually functions, they are a special object type that React recognizes and treats as a component, so they are not actually callable. In the past, only some of the exotic components supported all of the features of function components (propTypes, displayName, or defaultProps) so they had to be separated out.

@ferdaber It looks like these features works, so maybe it's time to change the typing?

Is anyone looking into this?

try it:

(Foo as React.ComponentType<Props>).defaultProps = {
    foo: '1'
};

```
type Props = {
hasProp?: boolean;
};

const MyComponent = ({ hasProp }) => (
<>
{hasProp && (

I have the prop


)}
I don't have the prop


);

MyComponent.defaultProps = {
hasProp: false
};

export default React.memo(props => );

Any updates on how to add a property to the result of a React.memo()? I'm currently using the "as" typecast to any, but that's hacky. Example use is where both are memoized.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ArtemZag picture ArtemZag  路  3Comments

victor-guoyu picture victor-guoyu  路  3Comments

Zzzen picture Zzzen  路  3Comments

jamespero picture jamespero  路  3Comments

csharpner picture csharpner  路  3Comments