Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

javascript - React Functional component: calling as function vs. as component

Say I have a functional component:

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

What is the difference between calling it directly as a function:

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

versus calling it as a component:

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

I'm mostly interested in performance implications, how React treats them differently internally, and perhaps how things might be different in React Fiber, where I hear functional components got a performance boost.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Calling it as a function is much faster, in fact there was a talk exactly about this few months ago. At this point functional react components can't be PureComponents so no extra optimizations really applied to them.

Basically if you can call functional component as a function that eliminates whole react lifecycle. If you think about it you are probably using this technique inside your render method even right now. Consider this:

... 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 method returns some react components, and could've been functional components but in this case is just some component class method.

See this article for detailed explanation: https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f

Also check out this babel plugin that is doing that: https://babeljs.io/docs/plugins/transform-react-inline-elements


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...