수업 내용
작업 내용
메인 페이지에서는 스터디를 3개의 조건으로 필터링하여 검색할 수 있는 기능과 스터디 리스트를 인피니티 스크롤로 페이징하는 기능을 구현하기로 했다. 두 기능을 유진님과 나누어 작업한 후, 연동하기로 하였는데 쉽지 않은 작업이었다. 하지만 유진님이 침착하게 이끌어주신 덕분에 기획한 기능대로 잘 구현되는 메인페이지를 볼 수 있었다!
Context API를 활용하는데 어려움이 있었는데, 유진님이 작업중인 프로젝트의 기능에 대입하여 이해하기 쉽게 알려주셨다. 코드도 봐주시고 유진님이 유용하게 사용하시는 방식도 공유해주셨다. 유진님 덕분에 앞으로 Context API를 유용하게 사용할 수 있을 것 같다! (유진님 정말 감사합니다! 😭 ) 6주 동안 팀원분들과 함께 작업을 하며 배운 점들이 아주 많다. 지금 이 시점에서도 6주 전의 나와 비교해보면 많은 변화가 느껴진다. 앞으로 공부할 방향성을 잡는데도 큰 도움이 되었고, 부족한 부분을 채워서 개인 프로젝트도 시작해야겠다는 마음과 용기도 생겼다. 프로젝트를 진행하며 시간이 벌써 이렇게 되었나하며 놀란 순간들이 많았는데, 그 만큼 ooLa 프로젝트에 몰입하며 지낸 것 같다.
첫 수업에서 자기소개를 할 때 “좋은 기회로 만난 사람들과 함께 많이 배우고 성장할 수 있는 경험이 되길 바란다.”고 했었는데, 나의 바람이 이루어져서 감사하다 🙏
좋은 기회로 좋은 분들을 만나 많이 배우고 성장할 수 있었던 카우치 코딩 👍
Context API는 리액트에 내장된 기능으로 프로젝트에서 props를 사용하지 않고 전역적(global)으로 데이터를 사용할 수 있도록 한다.
컴포넌트 트리가 깊을 경우, 속성 데이터을 Props를 사용해 여러 컴포넌트(상위 컴포넌트 → 하위 컴포넌트)에 걸쳐 넘겨줘야 하는 불편함을 해결할 수 있다.
Context API 사용법
createContext
생성하여 데이터 저장// MyStudyList.context.jsx
import React, { createContext, useState, useEffect } from 'react';
import {
getCreationStudy,
} from '../apis/myStudy';
// createContext
export const MyStudyListContext = createContext();
//Provider
export const MyStudyListProvider = ({ children }) => {
const [creationStudies, setCreationStudies] = useState([]);
async function creationStudy() {
const response = await getCreationStudy();
const content = response.data;
setCreationStudies(content);
return content;
}
useEffect(() => {
creationStudy();
}, []);
return (
// Context의 Provider로 감싸준다
<MyStudyListContext.Provider value={creationStudies}>
{children}
</MyStudyListContext.Provider>
);
};
App
컴포넌트에 Context의 Provider
를 제공// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
import { MyStudyListProvider } from './context/MyStudyList.context';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<MyStudyListProvider>
<App />
</MyStudyListProvider>
</React.StrictMode>,
);
useContext
로 데이터를 전달받아 사용import React, { useContext } from 'react';
import { MyStudyListContext } from '../../context/MyStudyList.context';
import StudyCard from '../studyCard/StudyCard.component';
const CreationStudyList = () => {
// useContext
const { creationStudies } = useContext(MyStudyListContext);
return (
<div>
{creationStudies.map(study => (
<StudyCard key={study.studyId} study={study} />
))}
</div>
);
};
export default CreationStudyList;
위 예시에서는 creationStudies
만 생성하여, Context API의 장점이 잘 보이지 않을 수 있는데, MyStudyList
에 데이터가 추가되는 경우 Context API를 더욱 유용하게 사용할 수 있다 🤓