How to stop useEffect from running twice on mount or first render in React

Dave Gray
Dave Gray
36.3 هزار بار بازدید - 2 سال پیش - Web Dev Roadmap for Beginners
Web Dev Roadmap for Beginners (Free!): https://bit.ly/DaveGrayWebDevRoadmap

Learn how to stop useEffect from running twice on mount or first render in React. The new React 18 strict mode runs useEffect twice and moved it further from production. Have they broken React? Possibly... this video provides a solution.

💖 Support me on Patreon ➜ Patreon: davegray

⭐ Become a full-stack web dev with Zero To Mastery Courses:
- Advanced React: https://bit.ly/AdvReactDev
- Jr to Senior Web Dev Roadmap: https://bit.ly/WebDevRoadmap-JrtoSr
- Master FAANG Coding Interviews: https://bit.ly/FAANGInterview

🚩 Subscribe  ➜ https://bit.ly/3nGHmNn

🚀 React JS for Beginners full course - 9 hours: React JS Full Course for Beginners | ...

📬 Course Updates ➜ https://courses.davegray.codes/

🔗 Starter & Completed Source Code: https://github.com/gitdagray/useeffec...

How to stop useEffect from running twice

(00:00) Intro
(00:16) Welcome
(00:29) Semantic Versioning
(01:43) The new useEffect behavior
(04:41) Why did React do this?
(05:46) Fetching Data with useEffect
(07:49) useEffect fix variation #1
(10:02) useEffect fix variation #2

Corrections:
(11:04) Variation #2 needs - if (effectRan.current === true || process.env.NODE_ENV !== 'development') ..so it will also work in production without requiring you to change the code. Github source code updated.

☕ Buy Me A Coffee: https://www.buymeacoffee.com/davegray

📚 Tutorial References:
🔗 React beta docs - "You might not need an effect": https://beta.reactjs.org/learn/you-mi...
🔗 React beta docs - "How to handle the Effect firing twice in development?": https://beta.reactjs.org/learn/synchr...

🔗 ES7 React JS Snippets Extension for VS Code:
https://marketplace.visualstudio.com/...

🔗 React Dev Tools Extension for Chrome:
https://chrome.google.com/webstore/de...

📚 General React References:
ReactJS Official site: https://reactjs.org/
React Wikipedia: https://en.wikipedia.org/wiki/React_(...)
React Jobs: https://www.ziprecruiter.com/candidat...

✅ Follow Me:
Github: https://github.com/gitdagray
Twitter: Twitter: yesdavidgray
LinkedIn: LinkedIn: davidagray
Blog: https://yesdavidgray.com
Reddit: Reddit: DaveOnEleven

Was this React 18 useEffect tutorial helpful? If so, please share. Let me know your thoughts in the comments.

#react #useeffect #twice
2 سال پیش در تاریخ 1401/04/10 منتشر شده است.
36,331 بـار بازدید شده
... بیشتر