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 cust…


This content originally appeared on DEV Community and was authored by Rakhi

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


This content originally appeared on DEV Community and was authored by Rakhi


Print Share Comment Cite Upload Translate Updates
APA

Rakhi | Sciencx (2021-04-25T12:15:50+00:00) Implement your own custom hook in React with typescript. Retrieved from https://www.scien.cx/2021/04/25/implement-your-own-custom-hook-in-react-with-typescript/

MLA
" » Implement your own custom hook in React with typescript." Rakhi | Sciencx - Sunday April 25, 2021, https://www.scien.cx/2021/04/25/implement-your-own-custom-hook-in-react-with-typescript/
HARVARD
Rakhi | Sciencx Sunday April 25, 2021 » Implement your own custom hook in React with typescript., viewed ,<https://www.scien.cx/2021/04/25/implement-your-own-custom-hook-in-react-with-typescript/>
VANCOUVER
Rakhi | Sciencx - » Implement your own custom hook in React with typescript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/25/implement-your-own-custom-hook-in-react-with-typescript/
CHICAGO
" » Implement your own custom hook in React with typescript." Rakhi | Sciencx - Accessed . https://www.scien.cx/2021/04/25/implement-your-own-custom-hook-in-react-with-typescript/
IEEE
" » Implement your own custom hook in React with typescript." Rakhi | Sciencx [Online]. Available: https://www.scien.cx/2021/04/25/implement-your-own-custom-hook-in-react-with-typescript/. [Accessed: ]
rf:citation
» Implement your own custom hook in React with typescript | Rakhi | Sciencx | https://www.scien.cx/2021/04/25/implement-your-own-custom-hook-in-react-with-typescript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.