Simplifying & Sharing Code with React’s Custom Hooks

Introduced in React 16.8, Hooks provides as a way to more easily share stateful logic between components. With React’s previous class based components, managing state that multiple components relied on was difficult. As a result, we often ended up writing code that was duplicated across multiple components, making it difficult to test. With the introduction of Hooks, we can rely on function based components to reduce code complexity and duplication. Since we’re able to easily isolate these reusable chunks of code, Hooks makes it easier to test.

Here are a few of the key benefits that React’s Hooks provides:

Benefits

  • an easy way to extract common logic to be shared between components

  • smaller, more manageable pieces of code that makes it easier to test

  • consolidated code for readability. Components tend to grow in size and complexity over time. Related code can reside in a class based function, but be scattered throughout different lifecycle methods: componentDidMount, componentDidUpdate, componentWillUnmount. The more this logic grows, the harder it becomes to split it into smaller, more manageable pieces to reason about.

  • avoids creating class based components — no longer needing to understand confusing aspects of classes (how this works or needing to remember to bind event handlers).

Writing a Custom Hook

React comes with a list of pre-defined hooks to handle common actions. It also provides the flexibility to create custom hooks to exactly fit our code’s needs.

In the example, we’ll write our own custom hook to show how we’re able to re-use code between components. Below, we have two separate React components: SubscriptionStatus and AccountsListItem. Each makes an API request to fetch an account’s status in order to tell whether that account is on a paid subscription or a free trial.

We see that each component relies on the same logic to determine an account’s status. As soon as each React component renders, we fetch and set an account’s details:

We can write our own custom hook to improve reusability by separating this logic into a useAccount hook. By convention, custom hooks are named with a “use” prefix and are able to call other hooks:

We’re now able to simplify our components by using our custom useAccount hook. Our components are no longer responsible for worrying about the implementation fetching an account’s details.

Hooks has been a welcomed way to write smaller, more maintainable code.

Previous
Previous

Understanding How React Renders With the Virtual DOM