DEV Community

loading...
Cover image for Implement your own custom hook in React with typescript

Implement your own custom hook in React with typescript

Rakhi
Engineer | Web, Browsers & Systems | she/her | I love books, sports and computers.
・2 min read

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. 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, 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:

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");
Enter fullscreen mode Exit fullscreen mode
  • Write the handler function:
  const handlers = () => ({
    toggle: () => {
      setState((res) => (res === "on" ? "off" : "on"));
    }
  });
Enter fullscreen mode Exit fullscreen mode
  • Memoize the handler function using useMemo:
  const handlers = useMemo(
    () => ({
      toggle: () => {
        setState((res) => (res === "on" ? "off" : "on"));
      }
    }),
    []
  );
};
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

That's all.

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

Here is how our component looks at the end:

Bookmark it in case you need it later or feel free to reach out atbrakhi

Discussion (5)

Collapse
polaroidkidd profile image
Daniel Einars

Is the useMemo really necessary here?

Collapse
atbrakhi profile image
Rakhi Author

Yes, memorizing toggler function is important as we pass it down to the component.

Collapse
polaroidkidd profile image
Daniel Einars

If we don't memorize it, would the components we pass the toggle into alway rerender when the toggle rerenders?

Thread Thread
atbrakhi profile image
Rakhi Author

If you want to check, if a component is rendering or not rendering, you can use console.count() in the component/hook file and check the results in console.

Collapse
anauthdes profile image
anauthdes

Nice example and explanation, thanks for sharing!

Forem Open with the Forem app