Creating Custom React Hooks — useToggle
Hi, today I’m going to explain React Custom Hooks and show basic example which is useToggle.
Well, why do we use custom hooks, what is the benefit for us? A custom hook is a Javascript function that starts with “use” and that can call other hooks. The main reason to create a custom hook is code reusability. Instead of writing the same code for different components which use the same logic, we can create a custom hook and reuse it. Let’s create toggle hook!
I’m going to create the toggle hook as I think it is repeated too often. A toggle allows the user to change a setting between two states which are checked and unchecked, each state can trigger its own set of actions.
We can use toggle hook to tick mark for checkbox, play or pause a video, flip the visibility of anything, etc.
I’m going to show you a toggle switch button that I created to explain better.
First of all, we need one variable and function. Our variable is to point to the Div and a boolean state that determines what we will display or not. The other one is the that makes the toggle function, so, it’s a function that closes if it is open and opens if it is closed.
useToggle returns the variable which finds out open or close and function which manage that. Then, onToggle returns the reverse open or close.
The index in the first variable of the returned array, in the second we will send an object. The first variable of the returned array is index which is on, second one is object which is onToggle. Now, we can use useToggle on App.js.
Finally, we can use custom toggle hook same as we use useState. I specified the initial state as true to stay open at first. By the way, you can give any name you want to the indexes, this is why we return an array in useToggle. Then, I created a button that its onClick triggers onToggle function. After a few scss tricks, it’ll look like this. You can access the all codes from my github link.
So, custom hooks is a easy way to re-use stateful logic in react hooks.
It was a little introduction to custom hooks with a pretty short and simple example. If you like my article, I can create and explain 5 custom hooks that the most used in more detail.
See you in my next article!