Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Reduce Code Redundancy with Custom React Hooks

    Paul McBridePaul McBride
    reactReact

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    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.