
์์ํ๋ฉฐ
Nomad Coder ๊ฐ์ ์ค useTab ์ปค์คํ ํ ๋ง๋๋ ๊ณผ์ ์์ ์ ๋ชฉ์ ์จ๋ ๊ฒ์ฒ๋ผ Re-rendering Issue์ Objects are not valid as a React ์ด์๋ฅผ ๋ง๋ฌ๋ค. ํํ ์ด์์ด๋ฏ๋ก ์์ฑํ๋ฉด์ ์ด๋ฐ ์๋ฌ๊ฐ ์ ๋ฐ์ํ๋์ง ์จ๋๊ณ ์ ํ๋ค.
์ฝ๋
import React, { useState } from "react"; | |
const content = [ | |
{ | |
tab: "Section 1", | |
content: "I am the content of the section 1" | |
}, | |
{ | |
tab: "Section 2", | |
content: "I am the content of the section 2" | |
} | |
]; | |
const useTabs = (initialTab, allTabs) => { | |
const [currentIndex, setCurrentIndex] = useState(initialTab); | |
if (!allTabs || !Array.isArray(allTabs)) { // (*1) | |
return; | |
} | |
return { | |
currentItem: allTabs[currentIndex], | |
changeItem: setCurrentIndex // (*2) | |
}; | |
}; | |
export default function App() { | |
const { currentItem, changeItem } = useTabs(0, content); | |
return ( | |
<div className="App"> | |
<h1> | |
Hello CodeSandbox{" "} | |
<span role="img" aria-label="eye emoji"> | |
๐ | |
</span> | |
</h1> | |
{content.map((section, index) => ( | |
<button key={index} onClick={() => changeItem(index)}> | |
{section.tab} | |
</button> | |
))} | |
<div>{currentItem.content}</div> <!-- (*3) --> | |
</div> | |
); | |
} |
Re-rendering Issue
์ ์์ ์ผ๋ก ์๋ํ ๋์ ์ฝ๋๋ ์ ๋ชจ์ต๊ณผ ๊ฐ๋ค. ์ฌ๊ธฐ์ 2๋ฒ ์ฃผ์ ํ์์์ ์ค์๋ฅผ ํ๊ฑฐ๋ ์๋ return ๋๋ ๋ฆฌ์กํธ ์ปดํฌ๋ํธ์ onClick
๋ถ๋ถ์ ์๋ชป ์ ์ ๊ฒฝ์ฐ Re-Rendering์ด ๊ณ์ ๋ฐ์ํ ์ ์๋ค.
useTabs
ํ
์ ๊ฐ์ฒด ํ๋๋ฅผ return ํด์ฃผ๊ณ , App()
ํจ์ํ ์ปดํฌ๋ํธ์์๋ ์ด๋ฅผ ์ฌ์ฉํ ์ ์๊ฒ ํ๋ค. ๋งจ ์ฒ์ UseTabs๋ useState
๋ฅผ ํตํด currentIndex๋ผ๋ value ํ๋์ setCurrentIndex๋ผ๋ _ํจ์_๋ฅผ ๊ฐ์ผ๋ก ๋ฐ๋๋ค. ๋ง์ผ ์ฃผ์ 2๋ฅผ changeItem: setCurrentIndex()
๋ก ์์ฑํ๋ฉด ํจ์๋ฅผ ๊ทธ๋๋ก ์คํํ๋ ์
์ด์ด์ ํจ์๋ฅผ ์ฐธ์กฐ๋ง ํ ๋์ ๋ฌ๋ฆฌ ํญ์ ์คํ๋๋ Re-rendering ์ด์๋ฅผ ๊ฒช๊ฒ ๋๋ค. ๋ํ, <button key={index} onClick={changeItem(index)}>
์ฒ๋ผ ์์ฑํด๋ ์๋์ ๊ฐ์ ์๋ฌ๋ฅผ ๋ณด๊ฒ ๋๋ค. ์ด๋ ๋งจ ์ ์ฝ๋๋ฅผ onClick={() => changeItem(index)}
๋ก ๋ณ๊ฒฝํ๋ฉด ํด๊ฒฐํ ์ ์๋ค.

Objects are not valid as a React Child
๊ฐ์ฒด ์์ฒด๋ฅผ ๋ ๋๋งํด์ฃผ๋ ค๊ณ ํด์ ๋์จ ์๋ฌ์ด๋ค. ๊ฐ์ฒด์ content๋ฅผ ํ๋ฉด์ ๋ณด์ฌ์ฃผ์ด์ผ ํ๋๋ฐ ๊ฐ์ฒด๋ฅผ ๋ ๋๋ง ์๋ํ๋ ค๊ณ ํ๊ธฐ ๋๋ฌธ์ด๋ค. currentItem์ content๋ฅผ ๋ณด์ฌ์ฃผ๋ฉด ํด๊ฒฐํ ์ ์๋ค.
