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
Become a member
to unlock all features

Level Up!

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


    Leverage an Existing Community Hook in Your React Function Component

    Elijah ManorElijah Manor

    Since the announcement of React Hooks a lot of community hooks have already been created. We will take a look at a list of these hooks and leverage a couple of them to use in our web application. The site is a great round-up of current community hooks that you can use today.



    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




    Instructor: We'll start up our dev server and run a little React app. It uses the deprecated battery status API. That still exists in Chrome at the moment. Let's take a look at the code. We'll open the playground function component. The majority of the code has been extracted out in a custom React hook called use battery.

    With the announcement of the hook's proposal, several sites have cropped up that keep a list of community-developed custom hooks that have been created so far. One such site, called Collection of React Hooks, created by Nik Graf, lists hooks from various sources in a searchable.

    If we search for battery, there's a community custom hook already created that we could use. You could also find ones for local storage, for document title, and much more.

    In this case, let's replace our custom hook with the one listed here from React-use. If we come back into our code and open the integrated terminal, we could NPM install React-use. Once installed, we can import use battery from React-use.

    As long as our APIs are the same, we should be able to delete our custom hook. It should just work. We could also delete the import for use states and use effect since those are now encapsulated in the community hook. Now, if we kick back up our dev server, we'll see on the right that, sure enough, it works as it did before.

    Next, let's see if we could find a community hook for our to-do list app. We'll switch our app to run our to-do list. Do you see how the title updates if there are incomplete to-dos? Let's see if we could replace our custom use document title hook with one from the community.

    The code for this is in the to-do list.hook.js file. Let's try importing use title as use document title so that it matches what we already had from React-use. Then we could go down and delete our version of the custom hook. If all goes well, title should still update as we mark off items. Sure enough, it does. Yay for community reuse!