EventEmitter에 대해

oversleep·2025년 2월 12일
0

app-development

목록 보기
4/38
post-thumbnail

React Navigation과 EventEmitter를 활용한 화면 간 데이터 동기화

화면 간 데이터 동기화 이해하기

1. 기본 동작 원리

  • Focus 상태 화면: 현재 보고 있는 화면
  • Background 상태 화면: 현재 보이지 않는 화면

2. 자동 새로고침이 되는 경우 (MatchingScreen)

useEffect(() => {
  fetchMatches();  // 데이터 가져오기
}, []);  // 화면이 처음 마운트될 때
  • Focus를 받으면 자동으로 useEffect 실행
  • 화면으로 돌아올 때마다 데이터 새로고침

3. 수동 새로고침이 필요한 경우 (MyPageScreen)

// events.ts
import EventEmitter from 'eventemitter3';
export const matchEventEmitter = new EventEmitter();

// MyPageScreen.tsx
useEffect(() => {
  // 이벤트 리스너 등록
  const listener = () => {
    loadParticipations();  // 데이터 새로고침
  };
  matchEventEmitter.addListener('matchCreated', listener);

  // 클린업
  return () => {
    matchEventEmitter.removeListener('matchCreated', listener);
  };
}, []);
  • Background 상태에서는 자동 새로고침 안 됨
  • EventEmitter로 수동 새로고침 트리거 필요

4. 이벤트 발생시키기 (WriteMatchForm)

if (response.status === 201 || response.status === 200) {
  // Background 상태인 MyPageScreen 새로고침을 위한 이벤트
  // (MatchingScreen은 화면 이동 시 자동 새로고침)
  matchEventEmitter.emit("matchCreated");
  
  Alert.alert("성공", "매치가 성공적으로 생성되었습니다", [
    { text: "확인", onPress: () => navigation.navigate("MatchingMain") },
  ]);
}

💡 주요 포인트

  1. Focus vs Background

    • Focus 상태: useEffect 등으로 자동 새로고침 가능
    • Background 상태: 이벤트로 명시적 새로고침 필요
  2. EventEmitter 사용 시기

    • Background 상태 화면의 데이터 갱신 필요할 때
    • 여러 화면에 동시에 변경 사항 알릴 때
  3. 주의사항

    • 이벤트 리스너는 반드시 cleanup 필요
    • 불필요한 이벤트 발생 주의
profile
궁금한 것, 했던 것, 시행착오 그리고 기억하고 싶은 것들을 기록합니다.

0개의 댓글