Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Could anyone can explain in detail the difference between functional component and class component in ReactJS?

When we use a functional component and when we use the class component?

See Question&Answers more detail:os

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

1 Answer

Here's a great article, "Presentational and Container Components", by Dan Abramov that can help you with that.

And here's a tl;dr; of the way I understand this:

  1. You'll have to use class CreatePostForm extends Component {} or React.createClass() if:

    • you need access to your component's lifecycle methods (ie.: componentWillMount or componentDidMount) – NOTE: Since React 16.8, this is no longer necessarily true and I would highly recommend reading on React Hooks as they can make things simpler once you get comfortable with them;
    • your component have direct access to your store and thus holds state (some people also call these components: smart components or containers).
  2. When your component just receive props and render them to the page, then you have a 'stateless component' (some people call these components dumb components or presentational components) and can use a pure function to represent it and it can be as simple as this

    import React from 'react'; export default () => <p>Hello from React!</p>;

Now, it's important to remember that a pure function can get way more complex than this and if you're comfortable with some ESNext syntax and destructuring and spreading attributes, you can have a presentational component that looks like this:

import React from 'react';
import AnotherComponent from './AnotherComponent';

export default ({ children, ...rest }) =>
    <AnotherComponent extraProp="anExtraProp" { ...rest }>
        { children }
    </AnotherComponent>;

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...