본문 바로가기
JavaScript

[React ERROR] 해결 React Hook "useState" cannot be called at the top level

by 오근성 2023. 8. 18.
728x90

간단 요약

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

를 참고하여 작성하였습니다.

 

728x90

댓글