๐Ÿœ Fix warning & useEffect cleanup function

summereuna๐Ÿฅยท2022๋…„ 5์›” 25์ผ

๐ŸŒŸ Twinkle (React, Firebase)

๋ชฉ๋ก ๋ณด๊ธฐ
24/42
post-thumbnail

์ž˜ ์ž‘๋™ํ•˜๋Š”์ง€ ํ™•์ธํ•˜๋Š” ์™€์ค‘์— ๊ฒฝ๊ณ ๋ฌธ์ด ๋–ด๋‹ค.

๋ฌธ์ œ ๋ฐœ์ƒ!


์ด๋ฉ”์ผ/ํŒจ์Šค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ€์ž… ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋‹ˆ ๊ฒฝ๊ณ ๋ฌธ์ด ๋–ด๋‹ค.

โš ๏ธ Warning: Can't perform a React state update on an unmounted component.
This is no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

at Auth (...URL)

๋ง์ธ ์ฆ‰์Šจ, ๋งˆ์šดํŠธ ํ•ด์ œ๋œ ๊ตฌ์„ฑ ์š”์†Œ์— ๋Œ€ํ•ด ๋ฆฌ์•กํŠธ state๋ฅผ ์—…๋ฐ์ดํŠธ ํ•  ์ˆ˜ ์—†๋‹ค๋Š” ๊ฒฝ๊ณ ์ด๋‹ค. ๋น„๋™๊ธฐ ๋กœ์ง ๋•Œ๋ฌธ์— ์ด๋Ÿฐ ํ˜„์ƒ์ด ๋ฐœ์ƒํ•˜๋Š”๋ฐ, ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ๋ˆ„์ถœ๋  ์ˆ˜๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ณ ์น˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ํ•œ๋‹ค.

๋ฌธ์ œ๊ฐ€ ๋˜๋Š” URL์„ ๋ˆŒ๋Ÿฌ ๋ดค๋”๋‹ˆ Auth.js์˜ ๊ฐ€์ž… ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅผ ๋•Œ, ๋ผ์šฐํŠธ๋Š” ์ด๋ฏธ ์ด๋™๋˜๋Š”๋ฐ, ๊ทธ๋Ÿฌ๊ณ  ๋‚˜์„œ setNewAccount(false)๋กœ state๋ฅผ ๋ณ€๊ฒฝํ•˜๋ ค๊ณ  ํ•˜๋Š”๊ฒŒ ๋ฌธ์ œ์˜€๋‹ค.

๐Ÿ“ src/routes/Auth.js

//form์— ์‚ฌ์šฉํ•˜๋Š” ์ด๋ฒคํŠธ
const onSubmit = async (event) => {
  event.preventDefault();
  //newAccount๊ฐ€ ์ฐธ์ด๋ฉด ๊ณ„์ • ์ƒˆ๋กœ ๋งŒ๋“ค๊ณ , ๊ฑฐ์ง“์ด๋ฉด ๋กœ๊ทธ์ธํ•˜๊ธฐ
  try {
    if (newAccount) {
      await createUserWithEmailAndPassword(auth, email, password);
      setNewAccount(false); //โš ๏ธ ์—๋Ÿฌ ๋ฐœ์ƒ ์ง€์ : ๋ผ์šฐํ„ฐ ์ด๋™ ํ›„ state ๋ณ€๊ฒฝํ•˜๊ธฐ ๋•Œ๋ฌธ
    } else {
      await signInWithEmailAndPassword(auth, email, password);
    }
  } catch (error) {
    setError(error.message);
  }
};

ํ•ด๊ฒฐ


์ด๋ฏธ ๋งˆ์šดํŠธ ํ•ด์ œ๋œ ๊ตฌ์„ฑ ์š”์†Œ์— ๋Œ€ํ•ด์„œ๋Š” ๋ฆฌ์•กํŠธ๊ฐ€ state๋ฅผ ์—…๋ฐ์ดํŠธ ํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์—
ํด๋ฆฐ์—… ํŽ‘์…˜์„ ์‚ฌ์šฉํ•˜์ž.

๐Ÿ“ src/routes/Auth.js

//form์— ์‚ฌ์šฉํ•˜๋Š” ์ด๋ฒคํŠธ
const onSubmit = async (event) => {
  event.preventDefault();
  //newAccount๊ฐ€ ์ฐธ์ด๋ฉด ๊ณ„์ • ์ƒˆ๋กœ ๋งŒ๋“ค๊ณ , ๊ฑฐ์ง“์ด๋ฉด ๋กœ๊ทธ์ธํ•˜๊ธฐ
  try {
    if (newAccount) {
      await createUserWithEmailAndPassword(auth, email, password);
      //โš ๏ธ ์—๋Ÿฌ ๋ฐœ์ƒ ์ง€์ : ๋ผ์šฐํ„ฐ์ด๋™ ํ›„ state ๋ณ€๊ฒฝํ•˜๊ธฐ ๋•Œ๋ฌธ, ๋”ฐ๋ผ์„œ โœ… ์‚ญ์ œ
      //โš ๏ธ setNewAccount(false);
    } else {
      await signInWithEmailAndPassword(auth, email, password);
    }
  } catch (error) {
    setError(error.message);
  }
};

//โœ… ํ•ด๊ฒฐ: ํด๋ฆฐ์—… ํŽ‘์…˜ ๋„ฃ์Œ
useEffect(() => {
  return () => setNewAccount(false);
}, []);

์ฐธ๊ณ  ์‚ฌ์ดํŠธ

https://kyounghwan01.github.io/blog/React/cant-perform-a-React-state-update-on-an-unmounted-component/#%E1%84%92%E1%85%A2%E1%84%80%E1%85%A7%E1%86%AF-%E1%84%8F%E1%85%A9%E1%84%83%E1%85%B3

profile
Always have hope๐Ÿ€ & constant passion๐Ÿ”ฅ

0๊ฐœ์˜ ๋Œ“๊ธ€