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?
- I want to show you how to create your own custom hook by giving you a simple example.
- Having a custom hook is useful as it hides information, which means you are utilizing encapsulation.
- It separates logic from the component. Your components will be super clean that way.
- 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:
- Create a folder name
Hooks
and inside it create a file calleduseToggle.ts
(remember all hook names start withuse
, let's keep the consistency) - Implement the handler method in
useToggle
file. - 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
Top comments (7)
Nice example and explanation, thanks for sharing!
Is the useMemo really necessary here?
Yes, memorizing toggler function is important as we pass it down to the component.
If we don't memorize it, would the components we pass the toggle into alway rerender when the toggle rerenders?
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.Nice explanation
Just letting you know that your link the the previous toggle article is a 404:
dev.to/rakhisharma/creating-a-togg...