// State hooks wrapper import { Component } from 'react' const stateContext = [] const tos = arr => arr[arr.length - 1] const useState = value => tos(stateContext)(value) const withState = component => class extends Component { constructor(props) { super() this.useState = this.useState.bind(this) this.registerState = this.registerState.bind(this) // Dummy render to register state usage and set initial state this.stateIndex = 0 this.preState = {} stateContext.push(this.registerState) component(props) stateContext.pop() this.state = this.preState } registerState(value) { this.preState[this.stateIndex++] = value return [value, () => value] } useState() { const stateIndex = this.stateIndex++ const curval = this.state[stateIndex] return [ curval, value => this.setState({ [stateIndex]: value }) ] } render() { this.stateIndex = 0 stateContext.push(this.useState) const rendered = component(this.props) stateContext.pop() return rendered } } export { withState, useState }