Reaction Functional component: calling a function as a component

Say I have a functional component:

const Foo = (props) => ( <div>{props.name}</div> );

What is the difference between calling it as a function:

const fooParent = () => (
    <div> {Foo({ name: "foo" })} </div>
)

against calling it as a component:

const fooParent = () => (
    <div> <Foo name="foo"/> </div>
)

I am mostly interested in the performance implications, how React views them differently inside, and maybe how things can be different in React Fiber, where I heard that functional components got a performance boost.

+4
source share
2 answers

Calling it as a function is much faster, in fact there was a conversation about this a few months ago. At the moment, functional responsive components cannot be PureComponents , so no additional optimizations are applied to them.

, , . , , , . :

... some component ... 

render() {

  const tabHeaders =<TabHeaders>{this.props.tabs.map(this.renderTabHeader)}</TabHeader>;
  const tabContents = <TabContents>{this.props.tabs.map(this.renderTabContent)}</TabContents>;

  return (<div>
    {this.props.tabsBelow?[tabContents, tabHeaders] : [tabHeaders, tabContents]}
  </div>);
} 

renderTabHeader , .

. : https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f

babel, : https://babeljs.io/docs/plugins/transform-react-inline-elements

+1

, , , . React 16 . UI, . , , componentDidCatch. .

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      error: false
    };
  }

  componentDidCatch() {
    this.setState({ error: true});
  }

  render() {
    return this.state.error
      ? "Error :("
      : this.props.children;
  }
}

const renderContent = () => {
  throw new Error();
}

const Content = () => {
  throw new Error();
}

// This will throw exception and not trigger error state
const Foo = () => (
  <ErrorBoundary>
    <div>{renderContent()}</div>
  </ErrorBoundary>
);

// This will trigger the error state
const Bar = () => (
  <ErrorBoundary>
    <div><Content /></div>
  </ErrorBoundary>
);

, , , .

, . React dev, , .

0

Source: https://habr.com/ru/post/1688249/


All Articles