React Hooks and Functional Components

Intro

Hooks is a relatively new feature in React which allows adding state to functional components. Hooks offer a few advantages over class components, such as easier code reuse.

This blog post is a nice overview of hooks. One of my main takeaways from the article is the three dot points at the start that explain rationale behind adding hooks to React.

I’d like to extend on some of the points mentioned in the article and rephrase them more as what improvements hooks offer:

  • Reduce complicated logic around lifecycle methods, as hooks provide a simplified way of dealing with the lifecycle of React components. For an example, checkout the useEffect hook, which is essential a combination of componentDidMount, componentDidUpdate and componentWillUnmount. This is real neat, since I find I duplicated a lot of logic between those 3 lifecycle methods.
  • Hooks are fully encapsulated (they are just functions after all), so each time a hook gets called, it has a isolated local state. Isolating state in React is useful for preventing bugs.
  • Custom hooks allow reuse of logic dependent on lifecycle methods. For example a set of components might need to subscribe to a stream of data and unsubscribe before unmounting, this logic can be reused between components by abstracting it into a custom hook.
  • Hooks are just functions, which makes it easy to abstract later. This will prevent premature optimization and code duplication. As its way easier to refactor hooks.

Some examples of hooks:

  • Loading and saving data to LocalStorage
  • Subscribing and unsubscribing to streaming data

Effects, e.g. the useEffect hook

useEffect allows defining side effects for a functional component. The most common side effects you’d encounter would be DOM manipulation (e.g. JavaScript charting frameworks), fetching data from APIs or anything involving timers (e.g. setInterval).

Custom Hooks

Writing custom hooks is a powerful feature of the hooks API, it allows writing reusable hooks that can be shared between components, more information in the docs.

Some examples of reusable hooks include:

  • Fetching from an API (and handling if the request is loading or an error has occurred)
  • Subscribing to a message bus, processing messages and unsubscribing before the component unmounts

Linting

Create React App has a really good built-in eslint preset for hooks (eslint-plugin-react-hooks)

Documentation