Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 25, 2021 12:15 pm GMT

Implement your own custom hook in React with typescript

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");
  • 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.

Here is how our component looks at the end:

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


Original Link: https://dev.to/atbrakhi/implement-your-own-custom-hook-in-react-with-typescript-1f1l

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To