Complete Intro to React v4

Complete Intro to React v4 Class vs Function Component

Topics:

This course has been updated! We now recommend you take the Complete Intro to React, v8 course.

Check out a free preview of the full Complete Intro to React v4 course:
The "Class vs Function Component" Lesson is part of the full, Complete Intro to React v4 course featured in this preview video. Here's what you'd learn in this lesson:

Convert the App component into a class component. You can use function components for components that don't need the more powerful parts of React like state and lifecycle methods.

Get Unlimited Access Now

Transcript from the "Class vs Function Component" Lesson

[00:00:00]
>> Brian Holt: Next thing I wanted to do here is I wanted to, what we're doing here, these are called function components. You'll also see them called stateless functional components sometimes. I think that's just a mouthful and a bit redundant. So I just call them function components, cuz it's a function that is a component.

[00:00:20] A lot of the times, you'll be using what are called class components. So we're gonna convert App here into what's called a class component. So I'm gonna say class App extends React.Component.
>> Brian Holt: Okay, and then I'm gonna make a function inside of that called render. And the body of render is just going to be this.

[00:00:47] So I'm going to take all this stuff that we have here, and I'm going to cut that. I'm just gonna paste that inside of our render function here,
>> Brian Holt: And then delete this App thing.
>> Brian Holt: So why do this? Well, these class components actually have a lot more flexibility in what they can do.

[00:01:23] They have more, I guess they're more powerful. Some people elect to make class components all the time. And they never use the other way of doing components, the function components like this. They'll never do it this way. They only do these ones. Other people prefer that if something doesn't need all of the extra bells and whistles, they'll just do the function components.

[00:01:45] Otherwise, they'll convert it to a class component. Cuz some people just don't like converting back and forth between class and functions based on what they need. People ask me what do I do, and I don't really know. [LAUGH] I kinda go back and forth on how I feel about it.

[00:02:01] When you have to convert between the two, it is kind of annoying. And I do like the simplicity of just, this is just something that returns something. So I do tend to use these function components sometimes if I have something that doesn't need state or any of the other life cycle methods or all the other more powerful parts of React.

[00:02:22] But in the end, what I'll say to you is that there are people that do both. One of them is not necessarily winning, so it's up to you to make a personal decision of how you feel about it. But it's worth experimenting with both and kind of getting familiar with them.