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
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 && (
MyComponent.defaultProps = {
hasProp: false
};
export default React.memo
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
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.