React functional vs class component

Tell us what’s happening:
Describe your issue in detail here.
What is the difference between a React functional and a class component?

  **Your code so far**

const ChildComponent = () => {
return (
  <div>
    <p>I am the child</p>
  </div>
);
};

class ParentComponent extends React.Component {
constructor(props) {
  super(props);
}
render() {
  return (
    <div>
      <h1>I am the parent</h1>
      { /* Change code below this line */ }
        <ChildComponent />

      { /* Change code above this line */ }
    </div>
  );
}
};
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36

Challenge: Create a Component with Composition

Link to the challenge:

functional component: it is actually just a function that takes input (props) and outputs JSX, therefore things like state cannot persist within it, and lifecycles don’t exist. (Unless you use hooks)

e.g.

const FunctionalComp=props=>{
//do stuff with props
return (JSX);
}

class components are Javascript classes, therefore you can initialize instances of them, and they can store things you don’t want React to forget on rerender in the state property. You can trigger different actions in different stages in the component lifecycle. It still takes props as input, and outputs JSX.

React currently is phasing out Class Components due to it being diffiult to reuse states between components, complex class components being difficult to understand, and the concept of a class component comes with inherent learning barriers. However it is a work in progress and plenty of code are written with Class Components so it is worthwhile to be familiar with Class Components.

Here is some reading on state and lifecycle of react class components

Here is some reading on hooks (in my opinion do not work with hooks until you are sufficiently comfortable working with stateful class components)

Practically speaking, there isn’t much of a difference (apart from how you write them), not now.

React used to need the class syntax for components that needed state (eg to store some values on the component). That can now be done with either components written as classes or components written as functions

Edit: when the FCC React curriculum was written, there was only the class version of components (function components naturally existed, but couldn’t have state). This is not the case now, hasn’t been for several years.

Edit edit: as a counterpoint to above, I don’t think there’s any point in class components any more, and functions + hooks are both simpler and more obvious, but YMMV: class components have a defined lifecycle (the methods occur in a specific order) so people sometimes find them more obvious.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.