React Hooks

class Counter extends React.Component {

  state = {
    count: 0
  };

  render() {
    return (
      <div>
        <div>{this.state.count}</div>
        <button onClick={_ => this.setState({ count: this.state.count + 1 })}>
          +
        </button>
        <button onClick={_ => this.setState({ count: this.state.count - 1 })}>
          -
        </button>
      </div>
    );
  }
}

useState()

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <div>{count}</div>
      <button onClick={_ => setCount(count + 1)}>+</button>
      <button onClick={_ => setCount(count - 1)}>-</button>
    </div>
  );
}

High Order Component?

class App extends React.Component {
  state = {
    visible: false
  };

  handleShow = () => {
    this.setState({ visible: true });
  };

  handleHide = () => {
    this.setState({ visible: false });
  };

  render() {
    const { visible } = this.state;
    return (
      <div>
        <Modal visible={visible} handleHide={this.handleHide} />
        <Button type="primary" onClick={this.handleShow}>
          Click me!
        </Button>
      </div>
    );
  }
}
export default class ModalContainer extends React.Component {
  state = {
    visible: false
  };

  show = () => {
    this.setState({ visible: true });
  };

  hide = () => {
    this.setState({ visible: false });
  };

  render() {
    const { visible } = this.state;
    const { children } = this.props;

    return children({
      visible: visible,
      show: this.show,
      hide: this.hide
    });
  }
}
class App extends React.Component {
  render () {
    return (
      <ModalContainer>
        {modal => (
          <div>
            <Modal visible={modal.visible} handleHide={modal.hide} />
            <Button type="primary" onClick={modal.show}>
              Click me!
            </Button>
          </div>
        )}
      </ModalContainer>
    );
  }
}
const MyForm = () => (
  <DataFetcher>
    {data => (
      <Actions>
        {actions => (
          <Translations>
            {translations => (
              <Styles>
                {styles => (
                  <form styles={styles}>
                    <input type="text" value={data.value} />
                    <button onClick={actions.submit}>
                      {translations.submitText}
                    </button>
                  </form>
                )}
              </Styles>
            )}
          </Translations>
        )}
      </Actions>
    )}
  </DataFetcher>
)

Why Hooks?

By Randy Lu

Loading comments...

More from Randy Lu