[React] Write a Custom State Hook in React
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
.
function useText(initialValue) { return useState(initialValue) } export function FeedbackCustomComponent() { const [text, setText] = useText('') 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])