230621 개발일지 TIL - react hook usestate cannot be called at the top level

The Web On Everything·2023년 6월 21일
0

개발일지

목록 보기
39/269

react hook usestate cannot be called at the top level

import { useState } from "react";
import "./App.css";

const initialState = [
  {
    id: "1",
    title: "title1",
    contents: "contents1",
    isDone: false,
  },
  {
    id: "2",
    title: "title2",
    contents: "contents2",
    isDone: false,
  },
  {
    id: "3",
    title: "title3",
    contents: "contents3",
    isDone: false,
  },
];

const [todos, setTodos] = useState(initialState);

function App() {
  return (
    <>
      <header>header</header>
      <main>
        <form>
          <input type="text" placeholder="title" />
          <input type="text" placeholder="contents" />
          {/* <button type="submit">추가</button> */}
        </form>
        <div>
          {todos.map((todo) => {
            return (
              <>
                <div>
                  <p>{todo.id}</p>
                  <p>{todo.title}</p>
                  <p>{todo.contents}</p>
                  <p>{todo.isDone}</p>
                </div>
              </>
            );
          })}
        </div>
      </main>
      <footer>footer</footer>
    </>
  );
}

export default App;

문제점
react hook usestate cannot be called at the top level라는 에러 발생

원인
useState를 함수 컴포넌트 내에서만 사용해야 하는데 함수 컴포넌트 밖에서 사용하고 있어 오류가 발생함.

해결방법
useState를 함수 컴포넌트 내부로 이동시켜 줌

import { useState } from "react";
import "./App.css";

function App() {
  const initialState = [
    {
      id: "1",
      title: "title1",
      contents: "contents1",
      isDone: false,
    },
    {
      id: "2",
      title: "title2",
      contents: "contents2",
      isDone: false,
    },
    {
      id: "3",
      title: "title3",
      contents: "contents3",
      isDone: false,
    },
  ];

  const [todos, setTodos] = useState(initialState);

  return (
    <>
      <header>header</header>
      <main>
        <form>
          <input type="text" placeholder="title" />
          <input type="text" placeholder="contents" />
          <button type="submit">추가</button>
        </form>
        <div>
          {todos.map((todo) => {
            return (
              <div key={todo.id}>
                <p>{todo.id}</p>
                <p>{todo.title}</p>
                <p>{todo.contents}</p>
                <p>{todo.isDone}</p>
              </div>
            );
          })}
        </div>
      </main>
      <footer>footer</footer>
    </>
  );
}

export default App;

느낀 점
어이없는 문제로 에러가 발생했는데 나중에 문제가 생기더라도 당황하지 않고 해결 할 수 있을 것 같다.

profile
오늘은 무슨 오류를 만날까?! 널 만나러 가는 길~ LOL

0개의 댓글