Home > other >  React.memo JSX.Element types
React.memo JSX.Element types

Time:09-23

If you have these simple components:


const Simple = (_props) => {
    return <div>Hello</div>;
}

const SimpleMemo = React.memo(Simple);
const SimpleMemo2 = React.memo((_props): JSX.Element => {
    return <div>Hello</div>;
});

Then SimpleMemo and SimpleMemo2 are inferred to be of different types. SimpleMemo is React.MemoExoticComponent<(_props: any) => JSX.Element> and SimpleMemo2 is React.NamedExoticComponent<object>.

Furthermore, you can't set some properties for SimpleMemo2 even though the code is the same:

    render() {
        return (
            <div>
                <Simple style={{backgroundColor: "green"}}/>
                <SimpleMemo style={{backgroundColor: "green"}}/>
                <SimpleMemo2 style={{backgroundColor: "green"}}/>
            </div>
        );
    }

This gives an error for <SimpleMemo2 style=:

Type '{ style: { backgroundColor: string; }; }' is not assignable to type 'IntrinsicAttributes & object'.
  Property 'style' does not exist on type 'IntrinsicAttributes & object'.

However it works fine for SimpleMemo. What is going on here? What's the difference between MemoExoticComponent and NamedExoticComponent and how can I make SimpleMemo2 work without having to assign the function to a variable?

CodePudding user response:

Your props are not typed. So SimpleMemo "works" but it really just accepts any prop. For example this works fine, but really shouldn't:

<SimpleMemo thisDoesNotExist="butNoError" />

SimpleMemo2 on the other hand works as expected - it's giving you an error because you're trying to pass a prop which the component is not expecting. To fix it, add all the props to the type:

type Props = {
  style?: React.CSSProperties;
};

const SimpleMemo2 = React.memo(({ style }: Props): JSX.Element => {
    return <div style={style}>Hello</div>;
});

Now you can use it without issues.

  • Related