Why does named component behaves differently than anonymous component

Viewed 101

I have two functional components. The only difference between them is that one is named. Like this:

const one = (props) => (<div>i am the first one</div>);

switch (type) {
  case 1:
    return one;
  case 2:
    return (props) => (<div>i am the second one</div>);
}

So the problem is the behavior is not the same. When the named component just rerenders itself after props change, the anonymous component recreates itself (call componentDidMount and componentDidUnmount). Could anyone explain what's happening there?

1 Answers

Named component is created once, and then you use a reference to it in a switch or somewhere else.

Unnamed function is created every time you call it.

Javascript functions are objects.

The object never equals another object except for the reference to itself.

Since the previous unnamed function doesn't equal the new one, React remounts it.

Related