본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Chat - 로딩 및 빈 상태

원문 보기 위키 갱신

Chat - 로딩 및 빈 상태 (Loading and empty states)

메시지가 로드되는 동안 로딩 스켈레톤을 표시하고, 대화에 메시지가 없을 때 빈 상태 콘텐츠를 표시합니다.

로딩 스켈레톤 표시

ChatMessageSkeleton은 메시지 콘텐츠가 로드되는 동안 자리 표시자 역할을 하는 애니메이션 섬머(shimmer) 선들을 렌더링합니다. 초기 데이터를 가져올 때나 히스토리 페이징으로 이전 메시지를 로드할 때 사용하세요.

인터랙티브 플레이그라운드

아래 데모를 사용해 섬머 선 개수를 조정해 보세요:

import * as React from 'react';
import Box from '@mui/material/Box';
import { ChatMessageSkeleton } from '@mui/x-chat';
import { PlaygroundCard } from 'docs/src/modules/components/chat-playground/PlaygroundCard';
import {
  DividerLabel,
  NumberControl,
} from 'docs/src/modules/components/chat-playground/controls';
import {
  useCustomizations,
  type CustomizationDef,
} from 'docs/src/modules/components/chat-playground/useCustomizations';

type ClassKey = 'root' | 'line';

const CLASS_DEFS: ReadonlyArray<CustomizationDef<ClassKey>> = [
  { name: 'root', description: 'The skeleton container.' },
  {
    name: 'line',
    selector: '.MuiChatMessageSkeleton-line',
    description: 'Each shimmer line.',
  },
];

export default function ChatMessageSkeletonPlayground() {
  const [lines, setLines] = React.useState(3);
  const classesCustomizations = useCustomizations<ClassKey>(CLASS_DEFS);

  const skeletonSx = classesCustomizations.toClassesSx();

  return (
    <PlaygroundCard
      title="ChatMessageSkeleton"
      description="Animated placeholder while a message is loading."
      previewMinHeight={160}
      classCustomizations={classesCustomizations.customizations}
      onClassesReset={classesCustomizations.reset}
      controls={
        <React.Fragment>
          <DividerLabel>props</DividerLabel>
          <NumberControl
            label="lines"
            value={lines}
            min={1}
            max={8}
            onChange={setLines}
          />
        </React.Fragment>
      }
      preview={
        <Box sx={{ width: '100%' }}>
          <ChatMessageSkeleton lines={lines} sx={skeletonSx} />
        </Box>
      }
    />
  );
}

컴포넌트 import

import { ChatMessageSkeleton } from '@mui/x-chat';

스켈레톤 렌더링

<ChatMessageSkeleton />

기본적으로 스켈레톤은 세 개의 섬머 선을 렌더링합니다. 마지막 선은 메시지의 자연스러운 모양을 흉내 내기 위해 더 짧습니다(너비 60%).

선 개수 구성

lines prop을 설정하여 표시할 섬머 선의 개수를 제어합니다:

<ChatMessageSkeleton lines={2} />
<ChatMessageSkeleton lines={5} />

메시지 로드 중 스켈레톤 사용

스켈레톤을 자동으로 렌더링하는 기능은 없습니다 — 어디에 나타날지는 직접 결정합니다. 데이터를 가져오는 동안 메시지 영역에 스켈레톤을 렌더링하고, 데이터가 도착하면 ChatMessageList로 교체하세요. 스와핑되는 컨테이너에 aria-busy를, 각 스켈레톤에 aria-hidden을 설정하여 보조 기술이 이 자리 표시자를 장식용으로 취급하게 하세요.

'use client';
import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import {
  ChatConversation,
  ChatConversationHeader,
  ChatMessageList,
  ChatMessageGroup,
  ChatComposer,
  ChatMessageSkeleton,
} from '@mui/x-chat';
import { ChatProvider } from '@mui/x-chat/headless';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';
import {
  minimalConversation,
  minimalMessages,
} from 'docs/data/chat/core/examples/shared/demoData';

const adapter = createEchoAdapter();

function LoadingMessages() {
  return (
    <Box
      aria-busy="true"
      sx={{
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        gap: 2,
        p: 2,
      }}
    >
      <ChatMessageSkeleton lines={2} sx={{ width: '70%' }} aria-hidden />
      <ChatMessageSkeleton
        lines={2}
        sx={{ width: '70%', alignSelf: 'flex-end' }}
        aria-hidden
      />
      <ChatMessageSkeleton lines={3} sx={{ width: '70%' }} aria-hidden />
    </Box>
  );
}

export default function LoadingSkeletonInList() {
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    if (!loading) {
      return undefined;
    }
    const timer = setTimeout(() => setLoading(false), 1500);
    return () => clearTimeout(timer);
  }, [loading]);

  return (
    <Box sx={{ width: '100%' }}>
      <Box sx={{ mb: 1 }}>
        <Button
          variant="outlined"
          size="small"
          onClick={() => setLoading(true)}
          disabled={loading}
        >
          Reload
        </Button>
      </Box>
      <ChatProvider
        adapter={adapter}
        initialActiveConversationId={minimalConversation.id}
        initialConversations={[minimalConversation]}
        initialMessages={minimalMessages}
      >
        <Box
          sx={{
            height: 500,
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
            border: '1px solid',
            borderColor: 'divider',
            borderRadius: 1,
          }}
        >
          <ChatConversation sx={{ height: '100%' }}>
            <ChatConversationHeader />
            {loading ? (
              <LoadingMessages />
            ) : (
              <ChatMessageList
                renderItem={({ id, index }) => (
                  <ChatMessageGroup index={index} messageId={id} />
                )}
              />
            )}
            <ChatComposer />
          </ChatConversation>
        </Box>
      </ChatProvider>
    </Box>
  );
}

히스토리 페이징으로 이전 메시지를 가져올 때는 목록 맨 위에 스켈레톤을 렌더링하세요. useChat()의 isLoadingHistory 플래그는 페이지가 가져오는 중인지 보고합니다. 초기 히스토리 가져오기 중과 loadMoreHistory 중에 true가 되므로, 동일한 플래그가 두 배치를 모두 처리합니다:

const { isLoadingHistory } = useChat();
// At the top of the message area:
{
  isLoadingHistory && <ChatMessageSkeleton lines={2} aria-hidden />;
}

전체 페이징 API는 히스토리와 페이징을 참고하세요.

슬롯 (Slots)

Slot Default element Description
root div The outer container
line div Each animated shimmer line

슬롯 교체를 통해 스켈레톤 모양을 커스터마이즈합니다:

<ChatMessageSkeleton
  slots={{
    root: MySkeletonRoot,
    line: MySkeletonLine,
  }}
/>

CSS 클래스

Class name Description
.MuiChatMessageSkeleton-root Root container
.MuiChatMessageSkeleton-line Individual line

접근성

ChatMessageSkeleton은 순전히 장식용입니다: 자체 role이나 aria-* 속성 없이 평범한 div 요소를 렌더링하므로, 보조 기술은 메시지가 로드되고 있음을 알 수 없습니다.

Chat 컴포넌트는 다른 수명 주기 단계를 자동으로 알려줍니다—메시지 목록은 도착하는 메시지를 위한 role="log" 공손 라이브 영역(polite live region)이고, 숨겨진 role="status" 영역은 스트리밍 전환을 알리며, 스트리밍 메시지는 aria-busy="true"를 지닙니다—하지만 이 중 어느 것도 초기 또는 히스토리 로드 중에는 발화되지 않습니다. 로딩 상태를 명시적으로 연결하세요:

import { visuallyHidden } from '@mui/utils';

<div aria-busy={isLoading}>
  {isLoading ? (
    <React.Fragment>
      <ChatMessageSkeleton aria-hidden="true" />
      <span role="status" style={visuallyHidden}>
        Loading messages…
      </span>
    </React.Fragment>
  ) : (
    children
  )}
</div>;
  • 스켈레톤에 aria-hidden="true"를 설정하세요 (추가 props는 루트 슬롯으로 전달됩니다). 그러면 섬머 선이 접근성 트리에서 제거됩니다.
  • 스켈레톤과 콘텐츠를 교체하는 컨테이너에 aria-busy를 설정하세요.
  • 알림에는 role="status" 요소를 사용하세요—공손 라이브 영역이므로 사용자를 방해하지 않습니다.

사용자가 동작 줄이기를 요청했을 때(prefers-reduced-motion: reduce) 섬머 애니메이션은 자동으로 멈춥니다.

빈 상태 (Empty state)

대화가 존재하지만 아직 메시지가 없을 때, ChatBox는 입력을 위한 컴포저가 준비된 빈 메시지 목록 영역을 렌더링합니다. 사용자가 새 대화를 시작할 때 보게 되는 상태입니다.

:::info 로딩 vs 빈 상태: 이 둘은 서로 다른 상태입니다. useChat() 또는 useChatStatus()의 historyStatus가 이 둘을 구분해 줍니다: 첫 렌더링부터 초기 페이지가 해결될 때까지 'loading'이고, 그다음 'loaded'(또는 'error')입니다. 'loading'인 동안에는 스켈레톤을 렌더링하고, 'loaded'이면서 메시지가 없을 때만 빈 상태를 렌더링하세요. ChatBox는 이를 자동으로 처리하며 초기 페이지 로드 중에는 빈 상태를 절대 표시하지 않습니다. :::

const { historyStatus, messages } = useChat();

if (historyStatus === 'loading') {
  return <ChatMessageSkeleton aria-hidden />;
}
if (messages.length === 0) {
  return <MyEmptyState />;
}

아래의 메시지 영역은 의도적으로 비어 있습니다 — 대화 헤더와 컴포저만 렌더링됩니다:

'use client';
import * as React from 'react';
import { ChatBox } from '@mui/x-chat';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';
import { demoUsers } from 'docs/data/chat/core/examples/shared/demoData';

const demoMembers = [demoUsers.you, demoUsers.agent];

const adapter = createEchoAdapter();

const emptyConversation = {
  id: 'empty-conv',
  title: 'New conversation',
  subtitle: 'Start a new conversation',
  participants: demoMembers,
  readState: 'read' as const,
  unreadCount: 0,
  lastMessageAt: '2026-03-15T10:00:00.000Z',
};

export default function EmptyState() {
  return (
    <ChatBox
      adapter={adapter}
      members={demoMembers}
      initialActiveConversationId={emptyConversation.id}
      initialConversations={[emptyConversation]}
      initialMessages={[]}
      sx={{
        height: 500,
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 1,
      }}
    />
  );
}

빈 상태의 핵심 특징:

  • 메시지 목록 영역은 보이지만 비어 있습니다
  • 컴포저는 입력할 준비가 되어 있습니다
  • 대화 헤더가 보입니다 (구성된 경우)
  • 목록 영역은 깔끔하게 접힙니다 — 남는 구분선, 스크롤 여유 표시, 자리 표시자 행이 없습니다

사용자 정의 빈 상태 콘텐츠

개별 컴포넌트로 스레드를 조합하여 사용자 정의 빈 상태 콘텐츠를 제공할 수 있습니다. 일반적인 패턴은 사용자가 대화를 시작하는 데 도움이 되는 제안 프롬프트를 표시하는 것입니다:

'use client';
import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import {
  ChatConversation,
  ChatConversationHeader,
  ChatMessageList,
  ChatMessageGroup,
  ChatComposer,
} from '@mui/x-chat';
import { ChatProvider, useChat } from '@mui/x-chat/headless';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';

const emptyConversation = {
  id: 'custom-empty-conv',
  title: 'New conversation',
  subtitle: 'Pick a prompt to get started',
  participants: [],
  readState: 'read' as const,
  unreadCount: 0,
  lastMessageAt: '2026-03-15T10:00:00.000Z',
};

function EmptyStateContent() {
  const { messages, sendMessage } = useChat();

  if (messages.length > 0) {
    return null;
  }

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        height: '100%',
        gap: 2,
        py: 4,
        pointerEvents: 'auto',
      }}
    >
      <Typography variant="h6">How can I help you today?</Typography>
      <Box
        sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', justifyContent: 'center' }}
      >
        <Button
          variant="outlined"
          size="small"
          onClick={() =>
            sendMessage({
              parts: [{ type: 'text', text: 'Explain quantum computing' }],
            })
          }
        >
          Explain quantum computing
        </Button>
        <Button
          variant="outlined"
          size="small"
          onClick={() =>
            sendMessage({
              parts: [{ type: 'text', text: 'Write a haiku about React' }],
            })
          }
        >
          Write a haiku about React
        </Button>
      </Box>
    </Box>
  );
}

const adapter = createEchoAdapter();

export default function CustomEmptyState() {
  return (
    <ChatProvider
      adapter={adapter}
      initialActiveConversationId={emptyConversation.id}
      initialConversations={[emptyConversation]}
    >
      <Box
        sx={{
          height: 500,
          width: '100%',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        <ChatConversation sx={{ height: '100%' }}>
          <ChatConversationHeader />
          <ChatMessageList
            overlay={<EmptyStateContent />}
            renderItem={({ id, index }) => (
              <ChatMessageGroup index={index} messageId={id} />
            )}
          />
          <ChatComposer />
        </ChatConversation>
      </Box>
    </ChatProvider>
  );
}

스트리밍 표시기

어시스턴트가 응답을 생성하는 동안 스트리밍 토큰이 메시지 버블 안에 점진적으로 렌더링됩니다. 사용자가 바닥 근처에 있는 한 메시지 목록은 새 콘텐츠를 따라 자동 스크롤됩니다.

스트리밍 상태는 다음에 반영됩니다:

  • ChatMessage.status—생성 중 'streaming'으로 설정됩니다
  • ChatTextMessagePart.state—활성 텍스트 파트에서 'streaming'으로 설정됩니다

이 값을 사용하여 타이핑 표시기나 깜빡이는 커서를 표시할 수 있습니다:

function TypingIndicator({ message }) {
  if (message.status !== 'streaming') return null;

  return <span className="typing-cursor" />;
}

라이브하고 구성 가능한 스트리밍 데모는 Streaming을 참고하세요.

함께 보기

  • 전체 메시지 레이아웃에 대한 자세한 내용은 메시지 표시를 참고하세요.
  • 스트리밍 텍스트 표시에 대한 자세한 내용은 Text and Markdown을 참고하세요.
  • 스트리밍 중 자동 스크롤 동작에 대한 자세한 내용은 메시지 목록을 참고하세요.
  • 키보드 탐색과 스크린 리더 모델은 접근성을 참고하세요.

ChatMessageSkeleton API

데모

이 React 컴포넌트의 사용 예시와 세부사항은 컴포넌트 데모 페이지를 방문하세요:

Import

import { ChatMessageSkeleton } from '@mui/x-chat/ChatMessageSkeleton';
// or
import { ChatMessageSkeleton } from '@mui/x-chat';

Props

Name Type Default Required Description
lines number 3 No

Note: The ref is forwarded to the root element.

Any other props supplied will be provided to the root element (native element).

Slots

Name Default Class Description
root 'div' .MuiChatMessageSkeleton-root The root container element.
line 'div' .MuiChatMessageSkeleton-line Each animated shimmer line element.

소스 코드

이 페이지에서 원하는 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보는 것도 좋습니다.

더 알아보기 (Learn more)