Share Logic Across Multiple React Components with Custom Hooks

Kent C. Dodds
InstructorKent C. Dodds
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 3 years ago

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.

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.