[React] Use the React Effect Hook in Function Components

Similar to the State Hook, the Effect Hook is “first-class” in React and handy for performing side effects in function components. The Effect Hook is called by passing a function as the first argument. Here, you can perform side effects. If needed, you can pass an optional second argument, which is an array of dependencies. This tells React, "Only run my effect when these values change."

A tip from Ryan Florence on using the dependency array:

"with which state does this effect synchronize with."

 

import React, { useState, useEffect } from 'react'
import { Form, Label, Textarea, Button, Title } from './Feedback.styles'

export function FeedbackEffectComponent() {
  const [text, setText] = useState('')
  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()
  }, [])

  // Handle form submission
  function handleSubmit(e) {
    e.preventDefault()
    console.log(`Submitting response to API: "${text}"`)
    setText('')
  }

  // Update text in state onchange for textarea
  function handleTextChange(e) {
    const updatedText = e.target.value

    setText(updatedText)
  }

  return (
    <Form onSubmit={e => handleSubmit(e)}>
      <Title>Effect Example</Title>
      <Label>
        Have feedback for our team? <br /> Let us know here 👇
        <Textarea value={text} onChange={e => handleTextChange(e)} />
      </Label>
      <Button type="submit">Submit</Button>
    </Form>
  )
}

 

posted @ 2019-10-31 20:51  Zhentiw  阅读(422)  评论(0)    收藏  举报