DEV Community

Cover image for Writing your own Custom Hooks
Hugo Ramon Pereira
Hugo Ramon Pereira

Posted on • Updated on

Writing your own Custom Hooks

Introduction

Since 2019 when React.js core team launched the version 16.8 with the React Hooks, a lot has changed ever since. Hooks have significantly improved the way we write code with React.js.

Now we can manage the state in a cleaner and leaner way, handle side effects, avoid unnecessary re-renders, improve performance and the list goes on and on…

But what are React Hooks?

Hooks are functions that were built to help us manage the lifecycle of Functional Components. We still have the Class-based Components but we cannot use hooks with Class-based Components. All hooks have to start with the word use by the way.

Now let’s take a look at 2 example of hooks before we write our own:

useState( )

The useState Hook allows you to manage a state variable and a function to update the value of this variable and reflect in the component it is being used.

States are data that is being used in our components and we need to keep track of the changes these data suffers so that React can update and re-render the component to display this new data.

Image description

In the code above we have the name state variable having empty strings as default value, which is passed at the execution of useState and setName function.

We created an auxiliary function to use setName and get the input value and we are using onChange to watch for that and the as the value of the input we used the name to bind it to our state.

useEffect( )

The useEffect Hook allows you to execute actions we call side effects in your components manipulating the lifecycle of our components. We use the useEffect hook to fetch data from an API or some other source of data, update the DOM, and timed tasks, the effects will execute when the page is first loaded or when we specify a dependency in the dependency list.

useEffect( ) takes 2 arguments: a function and a dependency as mentioned above. useEffect will be observing this dependency and when it does change then the actions we specified in the first argument, which is a function will execute.

We can specify no dependency in the dependency list or array and if we do so, then the useEffect hook will be executed only once, when the page is loaded for the first time and this behavior is what the ComponentDidMount used to do in previous versions of React.js.

Image description

In the example above the dependency list which is the empty array has no dependencies, we can add dependencies or not.

useState and useEffect are the 2 most used React hooks and now I will introduce you to Custom Hooks:

Custom Hooks

Hooks are reusable functions. React.js provides a list of Hooks, you can make a research and see if one of them suits your needs, if not you can build your own and that is exactly what we are going to do.

When you have component logic that needs to be used by multiple components, we can extract that logic to a custom hook.

In the code below you can see a custom hook called useWindowWidth which was created using the hooks useState and useEffect to store the width of the window by using the window.innerWidth and we used the useEffect to watch for changes in the width of the window and when it does change useEffect will be triggered and the state updating function setWidth will be executed.

Image description

useEffect will know the window changed its width because of the event listener ‘resize’ added inside of it.

And after the window is resized it is wise to remove events from our code to avoid memory issues like memory leak. We call a cleanup function where we add a removeEventListener. Events take up memory space, and we don't want unnecessary memory being misused and wasted which can and might cause issues as your applications grows.

In the code below we can see our Hook in action.

The purpose of this hook was to extract some logic to manipulate the classes of TailwindCSS.

In the classes of the Button component below we are using a ternary operator with windowWidth to add different background colors to our button when the width of the button changes for example, we can use our hook to manipulate the responsiveness of the app, it is acting like a breakpoint.

Image description

Conclusion

React Hooks are amazing and they also give us room to create our own hooks which was the main purpose of this article, to show you that you can abstract your code by using hooks that can save us a lot of time and countless lines of code and please remember to start it with the name use and something.

So whenever you feel the need to reuse code that is being repeated that is when the Hooks come in handy.

References

React.js
W3 Schools

Top comments (4)

Collapse
 
gifesom profile image
gifesom

Creating your own custom hook in React is a powerful way to manage state and logic. It allows you to encapsulate functionality and reuse it across components. To get started, you can define your custom hook, like "useGepcoBill," to handle specific tasks or operations related to "gepcobill." This modular approach promotes code reusability and simplifies complex logic within your application.

Collapse
 
hramonpereira profile image
Hugo Ramon Pereira

That is exactly the point, reusability, thanks 🤝🏼

Collapse
 
uiuxsatyam profile image
Satyam Anand

This is a well explained post ✌️. Thanks for sharing @ramonpereira88 bro.

Do you prefer using Custom Hooks or Media Query for responsiveness? 🤔 Any suggestion for me

Collapse
 
hramonpereira profile image
Hugo Ramon Pereira

Thanks for the comment Satyam. Lately I've been using TailwindCSS a lot and I've been using sm, md, lg it makes responsiveness a lot easier. I suggest TailwindCSS for you.