간단 요약
Hook을 React 함수 컴포넌트 내부에서 호출해야 합니다.
문제상황
React에서 `useState`와 같은 Hook을 사용하면서 아래와 같은 에러 메시지를 마주치게 될 수 있습니다:
Line 5:41: React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react\-hooks/rules\-of\-hooks
에러가 발생하는 코드:
import React, { useState, useEffect } from "react";
import Axios from "axios";
const [collegeList, setCollegeList] = useState([]);
useEffect(() => {
Axios.get("http://localhost:3001/api/get").then((response) => {
setCollegeList(response.data);
});
}, []);
CollegeList = collegeList;
export default CollegeList;
이 에러의 원인은 `useState`와 `useEffect`와 같은 Hook들이 React 함수 컴포넌트나 커스텀 React Hook 함수 내에서만 호출되어야 하는데, 이 코드에서는 함수 컴포넌트 밖에서 Hook을 호출하고 있기 때문입니다.
해결방법
이 문제를 해결하려면, Hook을 React 함수 컴포넌트 내부에서 호출해야 합니다.
아래와 같이 코드를 수정하면 됩니다:
import React, { useState, useEffect } from "react";
import Axios from "axios";
function CollegeListComponent() {
const [collegeList, setCollegeList] = useState([]);
useEffect(() => {
Axios.get("http://localhost:3001/api/get").then((response) => {
setCollegeList(response.data);
});
}, []);
return (
// 여기에 뷰 요소를 작성합니다.
);
}
export default CollegeListComponent;
이렇게 하면, `useState`와 `useEffect`가 함수 컴포넌트 내에서 호출되므로 위에서 발생한 에러가 해결됩니다.
React Hooks는 함수 컴포넌트에서만 호출해야 하므로, 주의하여 사용해야 합니다. Hooks를 사용하면 React 코드를 더 간결하고 명확하게 작성할 수 있으므로, 에러 메시지를 잘 이해하고 코드를 수정하면 문제없이 사용할 수 있습니다.
React Hook "useState" cannot be called at the top level - Stack Overflow
React Hook "useState" cannot be called at the top level
I am a beginner in react. I'm trying to send values of my database from one file to another using react-hooks, and getting the following error can anyone help me with this? Line 5:41: React Hook ...
stackoverflow.com
를 참고하여 작성하였습니다.
'JavaScript' 카테고리의 다른 글
[Next.js] Next.js에서 여러개의 쿼리 파라미터를 전달하는 방법 (url로 파라미터 전달) (0) | 2023.08.18 |
---|---|
[JavaScript] 수동으로 window 이벤트 발생시키기 (window.dispatchEvent) (0) | 2023.08.14 |
[React] React-Grid-Layout으로 드래그 가능한 반응형 그리드 디자인 구현하기 (0) | 2023.08.14 |
[React] react-joyride(유저 가이드, 튜토리얼 라이브러리) (0) | 2023.08.14 |
React에서 외부 함수를 사용하여 state 변경하기 (0) | 2023.08.11 |
댓글