The Daily TIL

February 15, 2019 by DaveDavereacthooks

Hooks are an official thing in React 16.8

The promise of hooks is that you can use React features, like state, without writing component classes. This allows you to separate your state logic from your components cleanly and in a reusable manner. The stateful logic exists as an independent function that can be tested in isolation and shared without changing component higherarchy.

Example

Let’s compare. Here’s a basic example of a component that uses state to keep track of button clicks.

// class version using state
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {      count: 0    };  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>          Click me
        </button>
      </div>
    );
  }
}

Here’s the same component, but using hooks instead of Component state.

// hook version using state
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>
  );
}

References