DEV Community

Cover image for UI Development: Stateful vs Stateless Widgets
Varun Palaniappan
Varun Palaniappan

Posted on

UI Development: Stateful vs Stateless Widgets

Let's quickly discuss stateful versus stateless widgets. If you're building screens or UI pages, start with a stateless widget—it's the best place to begin. So a widget doesn't have to be, excuse me, sorry, until you find the need for it to be stateful, which is essentially when there is a certain kind of interaction that happens with the user.

It shouldn't be, because I've seen a lot of widgets treated as stateful, but they really shouldn't be. You want more of them to be stateless. Even when you have a stateful widget that depends on a number of other stateless widgets, you can use them interchangeably.

So just create these widgets as stateless, and when the need arises for the user to interact with them—say they're making some changes, and you need those changes to be reflected—whether it's making API calls or based on the response from those API calls, your page or screen changes. Whether it's a mobile app or web app doesn't matter, and neither does the stack.

There are certain differences in how you would build a Flutter stateful widget versus a React Native widget, for instance, but fundamentally there aren't any differences, right? Because the idea is the same. Of course, when you bring other frameworks or libraries into the mix, this changes a tiny bit.

A little bit, say if you're using Redux for state management, for instance, but outside of those, just ignoring all of that, start with building a stateless widget and then make it stateful if you feel the need for it to be stateful. In my mind, I mean a good percentage of your widgets are going to be stateless, a good number of those.

I don't know what the math is, but I would imagine this is good for any product or any platform. Just don't start building them as stateful because it becomes difficult to manage them, and more often than not, they don't need to be stateful. So just keep that in mind.

Top comments (0)