Direct call of a functional component

前端 未结 2 698
忘掉有多难
忘掉有多难 2020-12-02 00:28

Stateless functional component is just a function that receives props and returns React element:

const Foo = props => ;
<         


        
2条回答
  •  萌比男神i
    2020-12-02 00:46

    Functional components are very useful when you don't need to use any of the lifecycle method or don't need to update the component state. As far as you don't need to them, you're good and yet best to go with stateless component.

    This will not hit the performance issue but gain the profit regarding its performance because we're just simply using function to render the component and not caring for its update, mounts, receive props, etc. But still there's no 100% gain using stateless component because react internally use class to render them.

    It's about 45% improvement.

    This post will also guide which one to choose between statefull component and stateless component.


    Further, you can not only receive the props but can also receive the ref:

    const stateless = (props, ref) => 
    

    Okay, let me refine my statement. Most of the blogs and even the docs states that stateless component don't have ref. Here are a few Q/A prepared regarding this issue:

    Do I need to use statefull component just to use ref?

    No. I already mentioned that we must require the class based component if we have to work with component state or hook some lifecycle method.

    How can I create ref in stateless component?

    const stateless = () => {
    
      // we can't do this.myRef = React.createRef()
      // so, let's create an object
      const RefObj = {}
    
      // now, create ref in {RefObj}
      RefObj.myRef = React.createRef()
    
      return 
    }
    

提交回复
热议问题