Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Share Logic Across Multiple React Components with Custom Hooks

    Kent C. DoddsKent C. Dodds

    React 16.7.0-alpha.0 was recently released and with it comes a set of experimental hooks and features. Use these with caution as they are likely to change in the near future.

    In React 16.6, there are hooks that allow you to use state in functions components in a simple way.

    With these hooks, you can share the logic easily. In this lesson, we'll break out the setCount hook into it's own function and use it in a Component.

    reactReact
    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
    Transcript

    Transcript

    Instructor: 00:00 One of the cool things about hooks is that it's really easy to share this logic across multiple components by making a custom hook. I'm going to make a function here called use counter. Here, we'll just bring over that code and we'll return an object with the count, which is our state and the increment.

    00:18 Then I'll get that count and increment from use counter, and our component is still working. That was a straight up JavaScript refactor. Pretty normal to take stuff out of one function, put it into another new one. Now we can use this in any other component that needs a counter.

    00:35 Let's go ahead and add a couple of customizations to our custom React hook. We'll have initial state here, so we can initialize it to whatever we want. Now I can initialize that to five, and we get it started out at five. We could also have a step.

    00:50 We're stepping by one. Let's go ahead and we'll take a step, and a step here. We'll take that step and set it to three. Every time I click, it's going to increment by three. We could also have it accept an object and have those be named arguments -- initial state and step. We can really do anything that we want to here.

    01:13 The fact that we're returning an object that has count and increment is just an implementation detail of this specific hook. We can return also the set count if we want to give more control over setting the count. We can really do anything that we want to with our custom hook.

    Discuss

    Discuss