FP in React
Basic FP
- Pure Function
- Curry
- Compose
Pure Function
- Given the same input, will always return the same output
- Does not have any observable side effect
Why Pure?
- Cacheable
- Portable
- Self-Documenting
- Testable
Curry
import curry from 'lodash/curry';
const match = curry(function(what, str) {
return str.match(what);
});
match(/\s+/g, 'hello world');
// [ ' ' ]
match(/\s+/g)('hello world');
// [ ' ' ]
const hasSpaces = match(/\s+/g); // Point free
hasSpaces('hello world');
// [ ' ' ]
hasSpaces('spaceless');
// null
Compose
import { flow, map, filter, prop, toUpper } from 'lodash/fp';
const users = [
{ name: 'a', isActive: false },
{ name: 'b', isActive: true },
];
const getUpperName = flow(prop('name'), toUpper);
const getActiveUsers = filter(prop('isActive'));
flow(getActiveUsers, getUpperName)(users)
// ['A', 'B']
FP in View
- Stateless Functional Component
- Recompose
Benefits
- Pure view
- Reuse view logic
- Constraint
FP in Dataflow
- Action
- Middleware
- Reducer
- Selector
Action
- Pure object
- Use filename as action type namespace
- All handler logic in container
- API action as Promise
Middleware
- Fetch
- Global Error
Reducer
- Predefined function
Selector
- Use FP to map data
- Can be cached by reselector
Summary
- Constraint
- Reusable
- Predictable
- Debug
FP in React
By zation
FP in React
- 476