DEV Community

Building User Interfaces with Pure Functions and Function Composition in React

Tyler McGinnis on March 17, 2017

If you're reading this you're probably familiar with the idea of functions. When to use and when to not use a function probably comes pretty natura...
Collapse
 
josegonz321 profile image
Jose Gonzalez

Perhaps one of my favorite things about React is it's given me a light introduction to functional programming (FP) and a fundamental piece of FP are pure functions.

TIL why I'm into functional programming!

I agree 100% with this article. I think pure functions is why I enjoy playing around with ReactJS instead of Angular2. (And JSX/TSX).

I'm taking this FP pure function approach and applying to C#. It's going to get better with C# 7.0 features!

Collapse
 
yelluw profile image
Pablo Rivera

Have you heard of my friend F#? It's what C# should be. 😄

Collapse
 
josegonz321 profile image
Jose Gonzalez
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.

Collapse
 
jhaeger profile image
Jason Haeger

I agree with your article. I'm not a "programmer". I'm more of a front-end designer, with a bit of JS for front end behavior and PHP for server-side rendering.

That having been said, playing around with React has made me a better "programmer" overall, merely as a side effect.

Collapse
 
alex_escalante profile image
Alex Escalante

If you haven't, you've gotta check recompose:

github.com/acdlite/recompose