Building a Custom Hook

In this lesson, you'll learn how to create a custom hook!

Introduction

Before we go into the other advanced patterns, it’s important to understand the default way to share functionality with hooks — building a custom hook.

Only by building on this foundation can we take advantage of the other advanced patterns we will discuss.

So far, we’ve built a compound component that works great! Let’s say you were the author of some open-source library, and you wanted to expose the “expand” functionality via a custom hook, how would you do this?

First, let’s agree on the name of your open-source (OS) library. We’ll leave it as Expandable — same as before.

Now, instead of having the logic for managing the expanded state in an Expandable component that returns a Provider, we can just export 2 custom hooks.

Get hands-on with 1200+ tech skills courses.