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
.
Why the dependency [setText] is used instead of [text] ?
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.
setText
is a function, when will the dependency happen? Once setText is called? Or once the reference of setText is changed?
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!
Why would it be a benefit to create custom hooks ?
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
Thank your for the answer