A React plugin to present hooks as higher order functions
npm install hooklyTypeScript
const Counter: FunctionComponent<{ name: string }> = ({ name }) => {
const [count, setCount] = useState(1);
return
Hi {name}, You clicked {count} times
;
}
`
It is a functional component with state. It mixes both the state, and the presentation in the same code.
We can fix this by splitting the presentation and the state into two components, the presentation component, and a container component.
`TypeScript
const Counter:
FunctionComponent<{ count: number, name: string, setCount: Dispatch> }> =
({ name, count, setCount }) => {
return
Hi {name}, You clicked {count} times
;
}
const CounterContainer: FunctionComponent<{ name: string }> = ({ name }) => {
const [count, setCount] = useState(1);
return
}
`
More abstracted again
`TypeScript
const Counter:
FunctionComponent<{ count: number, name: string, setCount: Dispatch> }> =
({ name, count, setCount }) => {
return
Hi {name}, You clicked {count} times
;
}
const CounterContainer: FunctionComponent<{ name: string }> = props => {
const [count, setCount] = useState(1);
const finalProps = { ...props, count, setCount };
return ;
}
`
It is possible to abstract the container component further, eventually creating a generic higher order component that will allow you to apply useState hooks to any component, allowing you to map the hook results to the properties of the component.
`TypeScript
interface IProps { count: number; name: string; setCount: setState; }
const Counter: FunctionComponent = ({ count, setCount, name }) =>
Hi {name}, You clicked {count} times
;
// ContainerCounter has type React.FunctionComponent<{ name: string }> but TS will infer this
const CounterContainer = stateWrapper(1, ([count, setCount]) => ({ count, setCount }))(Counter);
``