High Order Component
High Order
Function
What is High Order Function?
A function that does at least one of the following:
- Takes one or more functions as arguments,
- Returns a function as its result.
Examples
const map = (mapper) => (array) => {
const result = [];
for (item in array) {
result.push(mapper(item));
}
return result;
}
const add = (m) => (n) => m + n;
const add4 = add(4);
add4(2); // 6
Why High Order Function?
- Make logic more flexible
- Enhancement
Example
const mapArgument = (argumentMapper) => (targetFunction) => {
return (arg) => targetFunction(argumentMapper(arg));
}
const consoleNumber = number => console.log(`The number is: ${number}`);
const enhance = mapArgument(number => number * number);
const consoleDoubledNumber = enhance(consoleNumber);
consoleNumber(2) // The number is: 2
consoleDoubledNumber(2) // The number is: 4
High Order Component
What is High Order Component?
A higher-order component is a function that takes a component and returns a new component.
Example
import React from 'react';
import { connect } from 'react-redux';
const User = ({ username }) => <div>The user is: {username}</div>;
const UserPage = connect(
({ state }) => ({ username: state.user.username })
)(User);
Why High Order Component?
Share the same logic around components
Propblem
connect(state => ({
firstName: state.user.firstName,
lastName: state.user.lastName
}))(
withHandler({ onClick: () => {} })(
withProps(({ firstName, lastName }) =>
({ name: `${firstName} ${lastName}` }))(
pure(({ name, onClick }) => (
<div onClick={onClick}>The user is: {name}</div>
))
)
)
)
Recompose
Example
import { compose, withHandler, withProps, pure } from 'recompose';
compose(
connect(state => ({
firstName: state.user.firstName,
lastName: state.user.lastName,
})),
withHandler({ onClick: () => {} }),
withProps(({ firstName, lastName }) => ({
name: `${firstName} ${lastName}`,
})),
pure,
)(({ name, onClick }) => (
<div onClick={onClick}>The user is: {name}</div>
));
Benifits
- Extract all the logics out of view, make view as functional stateless component
- When all the logics are in the same place, it will be easy to find the duplicated logics and extract them
- With compose, we can easily reuse logics. Just compose them together
Thanks & QA
High Order Component
By zation
High Order Component
- 409