Hook useTabs

개발새발개발러·2022년 3월 30일
0

React

목록 보기
8/8
post-thumbnail

더미 데이터로 contents 생성한다.

const content = [
  {
    tab: "Section 1",
    content: "content 1"
  },
  {
    tab: "Section 2",
    content: "content 2"
  }
];

위의 더미데이터 배열을 map메소드를 사용해서 section1,2 버튼을 만듦

const App = () => {
  return (
    <div className="App">
      <h1>React useTabs hook</h1>
      {content.map((section) => (
        <button>{section.tab}</button>
      ))}
    </div>
  );
}

export default App;

useTabs hook 생성

const useTabs = (initialTab, allTabs) => {

  if (!allTabs || !Array.isArray(allTabs)) {
    return;
  }

 **//주의!!**
 **const [currentIndex, setCurrentIndex] = useState(initialTab);// 초기 tab값 세팅**

  return {
    currentItem: allTabs[currentIndex], //현재세팅된 인덱스 값으로 얻은 tab정보
    changeItem: setCurrentIndex //버튼 클릭시 index값 변경
  };

};

⇒useTabs hook작업중 마주친 에러

React Hook "usestate" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?

다음과 같은 에러는 usestate뿐만 아니라 useMemo, useEffect등 hook을 사용할때도 동일하게 적용된다.

이런 에러가 뜨는 이유는 Hook이 조건부로 선언되어있기때문이다.

위의경우 해당 에러가 발생한 이유는 함수 실행 중, Hook 선언 전에 조건을 통해 먼저 return되었기 때문!

따라서!

React Hook의 2원칙

  1. Hook은 최상위에서만 선언되어야 한다.
  2. 오직 React 함수 내에서만 Hook을 호출해야 한다.

button에 onClick을 걸어서 changeItem을 실행

⇒클릭한 button의 index값으로 state값 변경

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>
  );
};

0개의 댓글