React Hooks

Experience Report, 2 Months In

Hooks in one sentence?

Quick Hooks Primer

  • A new API exposed by React, as a number of named exports (currently 10)
import React, { useState } from "react";
  • All hooks are plain, side-effectful functions following the use* naming convention, with varying arguments and return values
function Example() {
  const [count, setCount] = useState(0);

  return (
      <button onClick={() => setCount(count + 1)}>
        Clicked {count} times
      </button>
  );
}
  • Introduced in October 2018, still "experimental"
  • Expected to hit a stable release next month
  • Already used at Facebook for a while, significant API changes very unlikely
  • You can only call a hook function during a functional React component render call
  • You always need to call hooks in the same order, never conditionally or in a loop
  • You can extract parts of code that uses hooks to an external function and call it from a component - a pattern called "custom hooks"
  • No new features, just an alternative interface to existing ones
  • Alternative to class components and HOC/render props
  • More ergonomic and composable API for stateful code reuse
  • Backwards compatible i.e. all existing code using classes will continue to work

Let's build something with hooks!

Hooks are experimental

But yeah, it was hard to resist, so...

Learnings after

2 months with hooks

on several projects

The API surface of
React I use actually
got smaller

Hooks feel native in React world

 

Built-in hooks and Custom hooks  
Built-in components and User defined components

 

Hooks help making right decisions about state location

Hooks encourage playing with code

Fetching data with hooks is a bit awkward

(for a good reason)

You will forget to add a dependecy to an
effect hook

(but you will learn to check it)

useReducer and don't useState when state gets bigger

(actually useState is just a special case of useReducer)

Maciek Pekala

@penzington

Made with Slides.com