Reduce Code Redundancy with Custom React Hooks

Paul McBride
InstructorPaul McBride

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

In this lesson, we'll cover how to create a custom React hook for managing the state of any input. This is one of the most powerful features of react hooks as it allows you to easily share functionality in a reusable way.

Instructor: [0:00] Here we have a simple app with three inputs. Their value is restored instead, and they're updated using their respective updater functions.

[0:10] As we can see, this all works as it should do, but we're repeating ourselves a lot in code. Especially in these handler functions, we're pretty much calling the same thing over and over again.

[0:21] Let's see how we can solve this with the custom hook. I've created a function called the useInput. The convention with React hooks is that they start with the word use.

[0:35] Next, let's create a way to store [inaudible] . We need to create a function to update that state. Finally, this function is going to return an object which contains these values. Let's see how we'd use this hook.

[0:54] First, let's update these calls to useState. We can get rid of these updater functions. Finally, we just need to update our inputs to make sure that we're referencing the correct value and onChange function.

[1:19] Everything is working exactly as it did before. We have a lot less code to deal with. However, we can make this even more succinct. Because this hook returns an object, and the keys of that object match be expected props on the inputs, we can just spread the object into the input.

[1:41] Again, this works exactly as it did before. Right now, this custom hook is located in the same file, but it could be placed anywhere and import it into any component.

~ 5 months ago

The reduction of redundant code using Custom Hooks was amazing. I had two watching the beginning portion twice. It is mind-blowing, how much you can do with simplified logic once a custom hook is in place.