zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[React] Write a Custom State Hook in React

React in State Write hook Custom
2023-09-14 09:00:48 时间

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])