
USESTATE
-useState는 state를 함수 컴포넌트 안에서 사용할 수 있게 해준다.
-useState는 클래스 컴포넌트의 this.state가 제공하는 기능과 똑같다.
-useState()Hook의 인자로 넘겨주는 값은 state의 초기 값이다. 함수 컴포넌트의 state는 클래스와 달리 객체일 필요는 없고, 숫자 타입과 문자 타입을 가질 수 있다.
import React, { useState } 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);
//useState Hook을 이용하면 state 변수와 해당 state를 갱신할 수 있는 함수가 만들어집니다.
//또한, useState의 인자의 값으로 initialTab을 넘겨주면 currentIndex 값을 initialTab으로 초기화할 수 있습니다.
return {
currentItem: allTabs[currentIndex],
changeItem: setCurrentIndex
};
};
const App = () => {
const { currentItem, changeItem } = useTabs(1, content);
return (
<div className="APP">
{content.map((section, index) => (
<button onClick={() => changeItem(index)}>{section.tab}</button>
))} //사용자가 버튼 클릭을 하면 changeItem 를 호출하여 state 변수를 갱신합니다.
<div>{currentItem.content}</div>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
실행화면


참고-노마드코더