Hello Everyone! I'm writing this blog after a 16 hour day at school, so please excuse me if I sound like I'm delirious. I will try my best to explain the subject in the most efficient and professional way possible. This was the end of my fourth week at Operation Spark. It has still been a hard transition to digital class (we're still in quarantine), but I'm trying my best to make it through. This past week we learned to make a Youtube clone in several different libraries and frameworks. One of the libraries that we used was React JS, something I had heard a lot about but I had never actually learned about. When I was trying to understand how and when to create a stateless component, all of the answers just said a stateless component is a component without a state; and that's not very helpful! So in this blog I will try my best to actually explain what the difference is between a stateless component and a stateful component, and when you should use each.
But first, let's talk about components! A component is basically just a piece of functionality in your app or website. Let's say your on Youtube, the video player might be a component. Or the list of recommended videos could be a component, with each video in that list being a component.
Here is an example* of a component:
- (I had to comment everything out to get the HTML to show up)
In this example, this component is creating a div of video-list and mapping through our video data and creating an entry in the video list for every video in the data.
The component in the example is a stateless component, but it will be easier to explain stateless if we first talk about stateful! Please forgive me for going all over the place.
So a state is an object that is owned by the component where it is declared. The scope of a state is limited to its current component. The values in a state object cannot be passed down to children. Before I go any further let's look at an example of a component that has state.
In this example, we are giving our state a movies key with an array as its value. We're then rendering a div for every element in the array. One important thing to note here is that every component with state has to be a class!
Now that we know a little bit about state, let's talk about stateless!
A stateless component is simply a component without a state object, nut I know that's not the answer you were looking for. Stateless components get their info from passing in props into their component. These props, unlike state, can be inherited to their children and aren't owned by their component.
Let's take a look at another stateless component:
Instead of getting our values from our state, we're getting it from the props that are being passes down. Also, stateless components never have to be class, while they can be, it's basically useless.
I hope this was helpful!
Top comments (0)