Implement your own custom hook in React with typescript
Tags: react, webdev, typescript, javascript
Published: 2021-04-25 12:15:50

As a beginner, thinking about creating a custom hook sounded very complex to me. As I spent more time working with them, I realized it isn't that complicated after all.

In this blog post I am going to take a very simple example and  create my own custom hook out of it.

I wrote a blog post recently about creating a toggle button in React [here](https://dev.to/atbrakhi/creating-a-toggle-button-in-react-i8o). In this blog post I am going to convert my toggle function into a react hook.

Why am I writing this hook for this small function, is it even needed?
1. I want to show you how to create your own custom hook by giving you a simple example.
2. Having a custom hook is useful as it hides information, which means you are utilizing encapsulation.
3. It separates logic from the component. Your components will be super clean that way.
4. Writing hooks means you are testing more and your code is more flexible. You can extend functionality without changing any component, in case the requirement changes as it always happens!

Let's go!

If you read my blog [Creating a Toggle button in React] (https://dev.to/atbrakhi/creating-a-toggle-button-in-react-i8o), you are good to continue reading. If not, I would highly recommend reading it, it will take <2 mins. I promise this blog post will look easier afterwards.

Now, that you have read my previous blog post, you might have noticed my code for creating a toggle button looks like this:

{% codesandbox u74p9 view=editor %}

In order to create a custom hook out of it, we need to follow these steps:
1. Create a folder name `Hooks` and inside it create a file called `useToggle.ts` (remember all hook names start with `use`, let's keep the consistency)
2. Implement the handler method in `useToggle` file.
3. Use the `useToggle` hook in your component.

Let get started then!

**Step 1**.  Create `Hooks` folder and a file inside it, name it as `useToggle.ts`. 

**Step 2**. Implement toggle handler function in the `useToggle.ts` file:

- Add a state:

```
  const [state, setState] = useState("off");
```

- Write the handler function:

```
  const handlers = () => ({
    toggle: () => {
      setState((res) => (res === "on" ? "off" : "on"));
    }
  });
```

- Memoize the handler function using `useMemo`:

```
  const handlers = useMemo(
    () => ({
      toggle: () => {
        setState((res) => (res === "on" ? "off" : "on"));
      }
    }),
    []
  );
};
``` 

Now you must be wondering why we needed to memoize the function here?  By using `useMemo` we are making sure our function remembers the result of the last time it was called. It also comes in very handy in performance optimizations.

**Step 3**. Use the hook `useToggle` in the component:

```
const [toggleState, { toggle }] = useToggle();
```

That's all.

Here is how our `useToggle` hook looks like at the end.

{% codesandbox 3ev58 module=/Hooks/useToggle.ts view=editor %}

Here is how our component looks at the end:

{% codesandbox 3ev58 view=split %}

Bookmark it in case you need it later or feel free to reach out [atbrakhi](https://twitter.com/atbrakhi)