DEV Community

Discussion on: Building User Interfaces with Pure Functions and Function Composition in React

Collapse
 
asolove profile image
Adam Solove

Everything in here is great, and I'm really glad people are reaching this enlightenment that writing UIs with pure functions is possible, and even desirable, in many cases.

But, like many forms of learning, now that you know how to do this, you can't cling to it. You need to be able to keep walking, from using stateful objects for UIs because you don't know another way, to using stateless functions for UIs because you can, to eventually learning that sometimes you want state and it's useful. As you start to build large UIs, especially if they have reusable components shared across different applications, you'll see that having local state permits certain patterns of reuse and encapsulation that pure functions can't emulate. If you want a library component to encapsulate behavior and hide details, so it can be modified without requiring changes to every application that uses it, you're going to need some local state. And this is fine, even very helpful, if done well.

Just like how Haskell people have "monads" so they can write pure functions that also hide certain stateful details, React provides a declarative rendering model for a components users, while still providing state and stateful callbacks for component authors in cases where they need them. Becoming an expert means knowing the advantages and tradeoffs of these choices and seeing when you can use state to your advantage.

I recently wrote up a longer explanation of React's declarative/stateful component model and how it's implemented.