use Hooks?

use() 훅은 비동기 데이터 처리와 컨텍스트 사용을 크게 단순화하는 강력한 기능을 제공합니다. 이 훅은 Promise와 같은 리소스를 읽어올 수 있으며, Suspense 및 오류 경계(error boundaries)와 원활하게 통합됩니다.

use Hook의 주요 기능

use Hook 사용하기

기존 useEffect를 사용하여 비동기 데이터 처리

import { useEffect, useState } from "react";

const DataComponent = ({ data }) => {
  return (
    <ul>
      {data.map((todo) => (
        <li key={todo.id}>
          <p>ID : {todo.id}</p>
          <p>UserID : {todo.userId}</p>
          <p>Title : {todo.title}</p>
          <p>Completed : {todo.completed ? "true" : "false"}</p>
        </li>
      ))}
    </ul>
  );
};

function App() {
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch("<https://jsonplaceholder.typicode.com/todos/1>")
      .then((response) => response.json()) // response.json()은 Promise이므로 여기에 처리
      .then((data) => setData(data)) // 데이터를 받아 setData로 저장
      .catch((error) => console.log(error))
      .finally(() => setLoading(false)); // 요청이 끝나면 loading 상태 false
  }, []);

  if (loading) return <div>loading...</div>;

  return <DataComponent data={data} />;
}

export default App;

use Hook를 사용하여 비동기 데이터 처리

import { Suspense, use } from "react";

async function getTodos() {
  try {
    const response = await fetch("<https://jsonplaceholder.typicode.com/todos>");
    if (!response.ok) throw new Error("Error");
    const todos = await response.json();
    return todos;
  } catch (error) {
    console.log(error);
    return [];
  }
}

const Todos = ({ todoPromise }) => {
  const data = use(todoPromise);

  return (
    <ul>
      {data.map((todo) => (
        <li key={todo.id}>
          <p>ID : {todo.id}</p>
          <p>UserID : {todo.userId}</p>
          <p>Title : {todo.title}</p>
          <p>Completed : {todo.completed ? "true" : "false"}</p>
        </li>
      ))}
    </ul>
  );
};

export default function App() {
  const todoPromise = getTodos();

  return (
    <Suspense fallback={<p>Loading...</p>}>
      <Todos todoPromise={todoPromise} />
    </Suspense>
  );
}

Error Bounary로 에러 처리하기

use HookErro rBoundary로 에러를 처리할 수 있습니다.

Error Boundary는 에러가 발생한 부분 대신 오류 메시지와 같은 fallback UI를 표시할 수 있는 특수 컴포넌트입니다.