DEV Community

independnt
independnt

Posted on

Stateless Components

When first starting out in React, and even beyond, I had mostly made all of my components stateful, even though the component had no need to maintain a state. But is that a bad thing? Well, short answer is yes, and for more reasons than one.

A stateless component is something that can be declared as a function, and can act as a full on stateful component, granted it’s given the necessary props. Besides the obvious of not retaining it’s own state, stateless components also don’t adhere to the component lifecycle methods. It also has no backing instance (object in memory where the state is stored). So essentially, a stateless component is just a function that’s returning JSX expressions.

Being able to create stateless components allows us to not only save memory, which is always a good thing, but it allows us to keep our code clean and simple. Recently I was working on a React Application that required a navbar, and prior to exporting the nav into it’s own stateless component, it looked like this:

App_Before

However, now, what we do, is we simply create a new file, and remove the html located within, and move it to a stateless component, and call it as a function like so:

App_Before

Notice that when i call it as a function, i use the function key word as opposed to arrow functions, the reason being that with arrow functions, we bind this, which we don't want in this particular instance. Now, we can simply replace all that code in App.js and insert our new stateless component.

App_Before

The reason I’m using .call(this) is to bind the context of this in App.js to the child, so we can access things like this.state from App.js.

Stateless components have really changed the way that I write in React, and I plan on using them as much as possible to save memory for my applications. Perfection!

Top comments (0)