Best Custom Hooks

Reading Time: 3 minutes

Learn how Custom Hooks can help you to solve specific problems in your React Projects. Here is a list of some of those hooks with an explanation about when and how to use them.

 

Custom Hooks

React hooks starting from version 16.8 allow you to use state and other React features without the need of writing a class. One of their features is to build your own Hooks (Custom Hook) which allow you to extract the component logic and turn it into reusable functions.

Now, let’s talk about custom hooks that can help you solve a specific problem.

usePrevious custom hook

By using usePrevious you can simulate the componentDidUpdate and compare the previous value with the current value; this custom hook uses the hook useRef to store the reference of the current value and return it.

When we use usaPrevios the user can save the value of the previous reference, and with this the user can compare it with the current user value, and depending on the validation we can set a new value.

useInput custom hook

useInput helps you to handle the value and onChange function of an input. Here we need to use the useState hook to save the attribute we are going to handle.

To use the created hook we have to import the file, assign it the attribute, that way it will return an object with the value and the onChange function that we are going to use in the input to be able to visualize it.

useTimeout custom hook

By employing useTimeout you can have a more customizable and better-managed timeout, in which you pass a callback and the delay the timeout will have.

We use the useTimeout custom hook to create a second counter in which we pass the function and the delay the counter will have in order to finally show it.

useFetch custom hook

By using useFetch we will get the data from the Api using Fetch and that way we will be able to handle the states, such as response, error, and loading. You only need to pass the URL of the API.

In the example now we can pass the url as a prop and get the response and save it on the hook state and use it on the component, we can also handle the error and the loading action to have a complete handle state.

Conclusion

Custom hooks have cleaner code and they are reusable. You can use custom hooks inside of your hooks, so more code is recycled, becoming faster and more dynamic too; but remember you cannot use hooks inside a class component.

0 Shares:
You May Also Like
Read More

RegEx Basics Guide

Reading Time: 6 minutesThis guide is a quick compilation of many Regular Expresions examples and how to use them to be…