FRONTEND_1 Telegram 3959
🔥 React: useEffect с async-функцией — антипаттерн!

Многие пишут так:


useEffect(() => {
async function fetchData() {
const res = await fetch('/api/data')
const json = await res.json()
setData(json)
}

fetchData()
}, [])


💥 Это работает, но неявно. Возникают проблемы:
- нет отмены запроса при анмаунте;
- сложно обрабатывать race conditions;
- нельзя обрабатывать ошибки на уровне useEffect.

Лучше — использовать AbortController и обычную функцию:


useEffect(() => {
const controller = new AbortController()

fetch('/api/data', { signal: controller.signal })
.then(res => res.json())
.then(setData)
.catch(err => {
if (err.name !== 'AbortError') console.error(err)
})

return () => controller.abort()
}, [])


🧠 Профит:
- безопасное отключение;
- контроль ошибок;
- читаемый код.

👉 @frontend_1
👍17👎3🔥1



tgoop.com/frontend_1/3959
Create:
Last Update:

🔥 React: useEffect с async-функцией — антипаттерн!

Многие пишут так:


useEffect(() => {
async function fetchData() {
const res = await fetch('/api/data')
const json = await res.json()
setData(json)
}

fetchData()
}, [])


💥 Это работает, но неявно. Возникают проблемы:
- нет отмены запроса при анмаунте;
- сложно обрабатывать race conditions;
- нельзя обрабатывать ошибки на уровне useEffect.

Лучше — использовать AbortController и обычную функцию:


useEffect(() => {
const controller = new AbortController()

fetch('/api/data', { signal: controller.signal })
.then(res => res.json())
.then(setData)
.catch(err => {
if (err.name !== 'AbortError') console.error(err)
})

return () => controller.abort()
}, [])


🧠 Профит:
- безопасное отключение;
- контроль ошибок;
- читаемый код.

👉 @frontend_1

BY Frontend разработчик




Share with your friend now:
tgoop.com/frontend_1/3959

View MORE
Open in Telegram


Telegram News

Date: |

How to Create a Private or Public Channel on Telegram? How to create a business channel on Telegram? (Tutorial) The creator of the channel becomes its administrator by default. If you need help managing your channel, you can add more administrators from your subscriber base. You can provide each admin with limited or full rights to manage the channel. For example, you can allow an administrator to publish and edit content while withholding the right to add new subscribers. Other crimes that the SUCK Channel incited under Ng’s watch included using corrosive chemicals to make explosives and causing grievous bodily harm with intent. The court also found Ng responsible for calling on people to assist protesters who clashed violently with police at several universities in November 2019.
from us


Telegram Frontend разработчик
FROM American