React hooks

Class

  • confusing "this"
  • not obvious class methods binding
  • lifecycle methods

Function component

  • simple in/out functions
  • lack of state
  • lack of lifecycle methods

Poor reusability of logic

Previous solutions

  • Mixins
  • Higher Order Components
  • Render Props

Mixins

  • Very early API
  • https://reactjs.org/blog/2016/07/13/mixins-considered-harmful.html
var PureRenderMixin = require('react-addons-pure-render-mixin');

var Button = React.createClass({
  mixins: [PureRenderMixin],
  componentDidMount: () {
    ...
  },
  render: () {
    ...
  }

});

Higher order components

  • Inject logic via wrapping component
  • Container/Component pattern
  • Easily composable
  • https://gist.github.com/pokorson/166da91279b0692e7dc5e9b5d138d22f

Higher order components

  • Nesting hell...
  • Naming collisions
  • Evaluated at parse time
  • https://gist.github.com/pokorson/2a5f40a16aa78034730704ba8853ab7e

Render props

  • Evaluated at render time
  • Better control for naming
class DataProvider extends React.Component {
    render() {
        const someData = ...

        return this.props.render(someData)
    }
}

<DataProvider render={data => (
  <h1>Hello {data.target}</h1>
)}/>

Render props

  • Still nesting hell...
  • Poor composition of multiple render props

Hooks API

State hook

Using state inside function components

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Effect hook

Acting on component lifecycle

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // initialize jquery dropdown
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

More hooks

  • useReducer

  • useContext

  • custom hooks - define your own hooks

Limitations

  • Declare only on top of component - no loop or conditions
  • Use only inside components

Useful links

  • https://reactjs.org/docs/hooks-intro.html
  • https://usehooks.com/
  • https://reacthooks.io/hooks/useArray

React hooks

By vrael560

React hooks

  • 414