# TIL - 2026.08.04

ssls·2026년 8월 4일

📌 오늘 학습한 주제

  • React useStateuseEffect를 활용한 상태 관리 및 비동기 데이터 로딩 (CommentPage.jsx)
  • Axios API 통신을 통한 백엔드 서버 연동 및 데이터 상태 업데이트
  • Props 및 커스텀 이벤트 핸들러를 활용한 자식 컴포넌트 제어 (ButtonPage.jsx, MaterialButton.jsx)
  • index.js 메인 진입점 파일 컴포넌트 마운트 스위칭

💡 오늘 배운 것 — 나만의 언어로

① 오늘의 목표

  • React의 useStateuseEffect Hook을 활용해 백엔드 API에서 데이터를 비동기로 불러와 화면에 동적으로 렌더링하고, 커스텀 컴포넌트에 이벤트 핸들러를 전달하는 구조 파악하기

② 학습할 내용

  • 상태 관리 및 비동기 통신 (CommentPage.jsx): 단순 정적 배열 대신 useState를 활용해 댓글 상태(comments)를 관리하고, useEffect로 컴포넌트 마운트 시 Axios 기반의 api.get('/comment') 함수를 실행하여 서버 데이터를 비동기로 불러오는 흐름을 익혔다.
  • 이벤트 핸들러 Props 전달 (ButtonPage.jsx): 상위 컴포넌트에서 정의한 이벤트 함수(saveHandler, listHandler)를 하위 커스텀 버튼 컴포넌트(MaterialButton)의 Props로 전달하여 동적 동작을 수행했다.
  • 엔트리 포인트 컴포넌트 스위칭 (index.js): 메인 파일인 index.js에서 최상위 노드에 <CommentPage />를 마운트하여 최종 결과 화면을 구성했다.

💻 오늘 핵심 코드

1. 비동기 API 통신 및 useState, useEffect 활용 (CommentPage.jsx)

import { useState, useEffect } from "react";
import api from "../../api/axios";

export const CommentPage = () => {
  // 1. useState로 댓글 목록 상태 관리
  const [comments, setComments] = useState([
    { writer: "작성자1", comment: "강사님과 함께하는 즐거운 React..." },
    { writer: "작성자2", comment: "강사님과 함께하는 즐겁지아니한 React..." },
    { writer: "작성자3", comment: "강사님과 함께하는 즐거운 React..." }
  ]);

  // 2. 비동기 데이터 로딩 함수 정의
  const loadData = async () => {
    await api
      .get("/comment")
      .then((response) => {
        console.log("debug >>>> response", response.data);
        setComments(response.data); // 서버 데이터로 state 업데이트
      })
      .catch((err) => {
        console.log("debug >>>> err", err);
      });
  };

  // 3. 페이지 진입 시(마운트) loadData 실행
  useEffect(() => {
    loadData();
  }, []);

  // 4. UI 렌더링
  return (
    <div>
      {comments.map((comment, idx) => (
        <div key={idx} style={{ border: "1px solid #ccc", margin: "8px", padding: "8px" }}>
          <p><strong>{comment.writer}</strong>: {comment.comment}</p>
        </div>
      ))}
    </div>
  );
};

2. 커스텀 버튼 이벤트 핸들러 연동 (ButtonPage.jsx)

import MaterialButton from "../../components/material/MAterialButton";

const ButtonPage = () => {
    const saveHandler = () => {
        console.log('debug >>>> save button click');
    }
    const listHandler = () => {
        console.log('debug >>>> list button click');
    }

    return (
        <div>
            <MaterialButton 
                title='글 작성하기'
                onclick={(e) => saveHandler()} />
            <MaterialButton 
                title='글 목록보기'
                onclick={(e) => listHandler()} />
        </div>
    );
}

export default ButtonPage;

3. 메인 엔트리 포인트 렌더링 (index.js)

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';
import CommentPage from './pages/smaple/CommentPage';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <CommentPage />
);

reportWebVitals();

🛠️ 실습 / 결과물 & 참고 자료

③ 실습 / 결과물

  • 강의 실습코드: CommentPage.jsx에서 Axios를 활용해 /comment 경로에서 서버 댓글 데이터를 수신 후 화면에 목록 형태로 출력하고, index.js에 마운트하여 실제 구동 확인.

④ 참고 자료

  • React Official Docs / W3Schools: React useState, useEffect Hooks 및 Axios GET 통신 예제 참고

🔍 문제와 해결

  • 막힌 부분: CommentPage에서 map() 함수 사용 시 JSX return 구문 누락 또는 비동기 수신 전 state 업데이트 시점에 의한 렌더링 오류 검토.
  • 해결 방법: map() 콜백 내부에서 JSX 요소를 정상적으로 return하도록 수정하고, useEffect의 빈 의존성 배열([])을 지정하여 페이지 초기 마운트 시 1회만 안전하게 데이터를 로드하도록 처리함.

🎯 다음에 할 일

  • useEffect 의존성 배열(Dependency Array)의 역할과 동작 원리 한 번 더 정립하기
  • Axios POST 요청을 이용하여 사용자가 입력한 새 댓글 데이터를 서버로 전송하고 화면을 즉시 갱신하는 기능 구현해보기
profile
성장중

0개의 댓글