Write a Custom State Hook in React

Share this video with your friends

Send Tweet

Writing your own custom State Hook is not as a daunting as you think. To keep things simple, we'll refactor our text state value that uses useState and instead create a custom hook called useText.

Ben Suen
Ben Suen
~ 5 years ago

Why the dependency [setText] is used instead of [text] ?

Joe Previte
Joe Previte(instructor)
~ 5 years ago

Why the dependency [setText] is used instead of [text] ?

Great question, Ben!

If we take a look at our useEffect, you'll notice we're using setText in the callback function, but not using text.

useEffect(() => {
    async function getStarWarsQuote() {
      // Get initial text
      const response = await fetch(
        'https://starwars-quote-proxy-gi0d3x1lz.now.sh/api/randomQuote'
      )
      const data = await response.json()
      const quote = data.starWarsQuote
      setText(quote)
    }
    getStarWarsQuote()
  }, [setText])

We only need to pass dependencies that are used within the callback function. I hope that clarifies the reasoning.

Ben Suen
Ben Suen
~ 5 years ago

setText is a function, when will the dependency happen? Once setText is called? Or once the reference of setText is changed?

Joe Previte
Joe Previte(instructor)
~ 5 years ago

setText is a function, when will the dependency happen? Once setText is called? Or once the reference of setText is changed?

Yes, you're right. It is a function. The dependency would "change" if the reference to setText somehow changed. Exactly!

Yannis
Yannis
~ 5 years ago

Why would it be a benefit to create custom hooks ?

Joe Previte
Joe Previte(instructor)
~ 5 years ago

Same reason you might create a function or a component - reusability, better abrastraction, extracting it to share in the open source community.

Here's a great example from @dayhaysoos who used this course to create a custom hook called use-stripe-cart

Yannis
Yannis
~ 5 years ago

Thank your for the answer