Create a Custom useBroadcaster Hook

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

Instead of always combining useState and useEffect, when can create a utility useBroadcaster hook which allows us to pass in a broadcaster. This lesson walks through setting up a custom hook to make our code more reusable.

Instructor: [0:00] Let's create our own custom hook by taking all of this, cut this out. We can define a useBroadcaster() custom hook. This can take two arguments. One is the broadcaster. The other is the dependencies, which will default to an empty array.

[0:21] The insides of this function is just the pasted content of what we cut out down below. We just wrapped everything that was in there inside of this function. That means we can pull this out because this is now this broadcaster.

[0:36] We'll just cut that out, type in broadcaster, and we can pull this out because that's just our dependencies. Instead of the array, we'll type dependencies. We can use our useBroadcaster hook just by passing in a createInterval. We'll say one second.

[0:58] For us, it's going to return the state that I want to use down here. That means up here, we need to return the state that came from the useState hook. If I hit Save here, I have the exact same features and functionality. It's just that now, I have my own hook, or I can just pass in a broadcaster and get some state out.

egghead
egghead
~ 18 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today