
오늘은 useTabs을 만들어 보면서 useState에 대한 공부를 마무리하고 useEffect로 넘어가보려 한다 !
import { useState } from "react";
import React from "react";
import ReactDOM from "react-dom";
const content = [
{
tab: "Section 1",
content: "I'm the content of the Section 1"
},
{
tab: "Section 2",
content: "I'm the content of the Section 2"
}
];
const App = () => {
return (
<div className="App">
{content.map(section=>(
<button>{section.tab}</button>
))}
</div>
);
};
export default App;
useTabs
import { useState } from "react";
import React from "react";
import ReactDOM from "react-dom";
const content = [
{
tab: "Section 1",
content: "I'm the content of the Section 1"
},
{
tab: "Section 2",
content: "I'm the content of the Section 2"
}
];
const useTabs=(initialTab, allTabs)=>{
if(!allTabs || !Array.isArray(allTabs)){
return;
}
const [currentIndex, setCurrentIndex]=useState(initialTab)
return{
currentItem: allTabs[currentIndex],
changeItem: setCurrentIndex
};
};
const App = () => {
const { currentItem, changeItem }=useTabs(0, content); //함수에 인자를 넘겨줌.
return (
<div className="App">
{content.map((section, index)=>(
<button onClick={()=> changeItem(index)}>
{section.tab}
</button>
))}
<div>
{currentItem.content}
</div>
</div>
);
};
export default App;
content.map((section, index)에서 index는 0또는 1이 되어야하고 모든 버튼은 onClick 이벤트를 가짐. button 에서 누군가 클릭하면 index가 무엇이든지 상관없이 changeItem(Index) 을 실행.-> 이는 setCurrentIndex의 item을 바꿔줌. 따라서 currentItem의 currentIndex를 바꿔줌. 

useEffect는 componentWillUnmount와 componentDidMount, componentDidUpdate와 비슷.
const App = () => {
const sayHello = () => console.log("hello");
useEffect(() => {
sayHello();
});
const [number, setNumber] = useState(0);
const [aNumber, setAnumber] = useState(0);
return (
<div className="App">
<div>hi</div>
<button onClick={() => setNumber(number + 1)}>{number}</button>
<button onClick={() => setAnumber(aNumber + 1)}>{aNumber}</button>
</div>
);
};


componentDidMount의 역할을 해서 새로고침을 하면 sayHello를 실행하고 componentDidUpdate의 역할도 하기 때문에 버튼을 클릭하면 sayHello를 실행. effect가 됨. 두번째 인자는 deps로 만약 deps가 있다면 effect에는 deps리스트에 있는 값일 때만 값이 변하도록 활성화 됨.
const App = () => {
const sayHello = () => console.log("hello");
const [number, setNumber] = useState(0);
const [aNumber, setAnumber] = useState(0);
useEffect(sayHello, [number]);
문서의 제목을 업데이트 시켜주는 것을 담당하는 hook을 만들어보자!!
const useTitle = (initialTitle) => {
const [title, setTitle] = useState(initialTitle);
const updateTitle=()=>{
const htmlTitle=document.querySelector("title")
htmlTitle.innerText=title;
};
useEffect(updateTitle, [title]);
return setTitle;
};
const App = () => {
const titleUpdater = useTitle("loading...");
setTimeout(()=> titleUpdater("home"), 5000);
return (
<div className="App">
<div>hi</div>
</div>
);
};


다음에는 useEffect를 활용한 hooks를 몇가지 더 만들어보겠습니다 !!