[React] Use the React Effect Hook in Function Components
2024-09-26 03:42:04
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最新文章
- pt_table_checksum对检查表的chunk大小的限制
- 强连通 HDU 3639
- Leetcode Combination Sum
- jQuery 屏蔽鼠标快速经过
- Allegro中板子边框不封闭导致的z-copy无法用的问题
- java 进制转化
- css3学习笔记之多列
- 在virtual pc中搭建基于ubuntu 的git环境
- Windows端口转发
- php基础(六)Include
- 【转】动态字节码技术跟踪Java程序
- .NET Core+MySql+Nginx 容器化部署
- 《设计模式之禅》--设计模式大PK
- 在Debian/Ubuntu系统中安装*.sh与*.bin文件
- SAP MM Storage Location Missing in MD04 Result?
- OpenStack若干概念
- POI导出Word插入复选框
- 关于java内存泄露的总结--引用的类型:强引用,弱引用,软引用
- js一些常用方法总结
- HCNP学习笔记之史上最全华为路由器交换机配置命令大合集
热门文章