Elements of Functional Programming for React.js Developers
This presentation is also available at
Source code with most examples:
This work is licensed under a
Creative Commons Attribution - NonCommercial - ShareAlike 4.0 International License .
How can you trust your data
when it has its own mind?
The data, state and the computation are coupled together:
Each object is a little actor with its own state.
It exposes various methods
via which other actors can communicate with it.
They are all one big, happy family
that interacts with one another.
Sounds like a powerful idea.
There are some benefits of OOP
e.g. it is easy to implement stateful computation.
many actors, each with its own state
And it is!
You have to keep track of implicit context
When you implement a function
(method is just a function attached to an object)
you don’t know what
this will be.
this is like an implicit argument.
It will only be known at the time of calling the function.
Even worse, your data starts having brain of its own:
Hint: It will print “Buhahaha 🥳”
And it may be up to no good
Seriously, who needs this in their language?
Or instead of
Things are simple and you can compose them
A data is just a data:
A function is just a pure function:
a -> b
Functions don’t have state nor side - effects.
You can compose data:
You can compose functions:
Or even this:
With this setup:
All of these are equivalent:
But what if the function I want to compose takes some additional arguments?
The lambda way:
make your self a new function
The partial way:
The Indian cuisine way
Just kidding. It’s a way of Haskell Brooks Curry.
Using partial application and composition you can model any computation, no matter how complex.
And it will almost always be easier to reason about than OOP, because no state means less complexity.
Predictible behaviour, simple rules of composition and partial application.
What follows is that concerns are usually separated
You can mix them if you want to, but by default they are separated.
Sure. Sometimes you do. But ask yourself how often?
And if you really do, be explicit about it.
If you are working with React, use Redux.
(or whatever else is all the hype this week)
If you need effects (e.g. networking), use Thunks.
For presentation use functional components.
How to do FP in JS
Come join us at Category Theory Study Group
Meet some friendly people and learn the mathematical theory behind this stuff.