Home

(React) Cannot read properties of undefined 에러 완벽 해결 가이드

Published in react
March 08, 2025
1 min read
(React) Cannot read properties of undefined 에러 완벽 해결 가이드

안녕하세요, 코딩하는곰입니다! 😊
20년 넘게 React를 다루면서 가장 자주 마주치는 에러 중 하나가 바로 ‘Cannot read properties of undefined’입니다. 이 에러는 React 개발자라면 누구나 한 번쯤 경험해보셨을 텐데요, 오늘은 이 에러의 발생 원인부터 다양한 해결 방법까지 깊이 있게 다루어보겠습니다. 초보자부터 중급자까지 모두 이해할 수 있도록 상세히 설명드릴 테니 끝까지 함께해주세요!

1. 왜 ‘Cannot read properties of undefined’가 발생할까?

이 에러의 근본적인 원인은 존재하지 않는 객체의 프로퍼티에 접근하려고 할 때 발생합니다. React에서는 주로 다음과 같은 상황에서 나타납니다:

  1. 초기화되지 않은 state 접근

    function MyComponent() {
    const [user, setUser] = useState(); // 초기값 없음
    return <div>{user.name}</div>; // user가 undefined
    }
  2. 비동기 데이터 처리 미흡

    function UserProfile({ userId }) {
    const [user, setUser] = useState(null);
    useEffect(() => {
    fetchUser(userId).then(data => setUser(data));
    }, [userId]);
    return <div>{user.details.address}</div>; // 초기 렌더링 시 user가 null
    }
  3. 옵셔널 체이닝 미사용

    // 문제 코드
    const fullName = props.user.profile.name;
    // 해결 코드 (옵셔널 체이닝)
    const fullName = props.user?.profile?.name;
  4. 잘못된 props 전달

    <UserCard user={undefined} /> // 하위 컴포넌트에서 user.name 접근 시 에러

(React) Cannot read properties of undefined 에러 완벽 해결 가이드
(React) Cannot read properties of undefined 에러 완벽 해결 가이드


📱 앱 개발에 도전하고 싶다면, (자바 역사) 가전제품을 위한 언어에서 세계 최고의 프로그래밍 언어로 - Green 프로젝트의 시작를 참고해보세요.

2. 실제 프로젝트에서 적용하는 7가지 해결 전략

2-1. 기본값 설정 (가장 기본적이지만 효과적인 방법)

// State 초기화
const [user, setUser] = useState({
name: '',
profile: {}
});
// Props 기본값
UserProfile.defaultProps = {
user: {
name: 'Guest',
profile: {}
}
};

2-2. 옵셔널 체이닝 (Modern JavaScript)

// 중첩 객체 접근 시
const userCity = user?.address?.city || 'Unknown';
// 함수 호출 시
const result = apiResponse?.data?.getItems?.();

2-3. TypeScript로 사전 방지 (정적 타입 검사)

interface User {
name: string;
profile?: {
avatar?: string;
};
}
const UserAvatar: React.FC<{ user: User }> = ({ user }) => {
return <img src={user.profile?.avatar || '/default.png'} />;
};

2-4. 조건부 렌더링 패턴

function UserInfo({ user }) {
if (!user) return <LoadingSpinner />;
return (
<div>
<h2>{user.name}</h2>
{user.profile && <p>{user.profile.bio}</p>}
</div>
);
}

(React) Cannot read properties of undefined 에러 완벽 해결 가이드
(React) Cannot read properties of undefined 에러 완벽 해결 가이드


닉네임을 고르다가 마음에 드는 걸 놓쳤다면? 생성 이력을 저장해주는 닉네임 추천 도구가 딱입니다.

3. 고급 에러 핸들링 기법

3-1. 커스텀 훅으로 안전한 데이터 접근

function useSafeAccess(obj, path, defaultValue) {
return path.split('.').reduce((acc, key) =>
(acc && acc[key] !== undefined) ? acc[key] : defaultValue,
obj
);
}
// 사용 예시
const userName = useSafeAccess(user, 'profile.name', 'Anonymous');

3-2. 에러 바운더리와 함께 사용

class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <FallbackUI />;
}
return this.props.children;
}
}
// 사용 예시
<ErrorBoundary>
<UnstableComponent />
</ErrorBoundary>

3-3. 유틸리티 함수 라이브러리 활용

// lodash의 get 함수 사용
import _ from 'lodash';
const deepValue = _.get(object, 'path.to.deep.value', defaultValue);
// 직접 구현한 safeAccess
const safeAccess = (obj, path) =>
path.split('.').reduce((acc, key) => acc?.[key], obj);

(React) Cannot read properties of undefined 에러 완벽 해결 가이드
(React) Cannot read properties of undefined 에러 완벽 해결 가이드


게임이나 SNS에서 쓸 닉네임이 고민된다면, 카테고리별로 추천해주는 닉네임 생성기를 활용해보세요.

이렇게 ‘Cannot read properties of undefined’ 에러에 대한 다양한 해결 방법을 살펴보았습니다. 🎯
React 개발에서 이 에러는 결코 피할 수 없는 것이 아니라, 더 견고한 애플리케이션을 만들기 위한 기회로 삼을 수 있습니다.
여러분의 프로젝트에 맞는 최적의 해결책을 선택하시고, 궁금한 점이 있다면 언제든 댓글로 문의해주세요!
다음 시간에는 또 다른 유용한 React 팁으로 찾아뵙겠습니다. 코딩하는곰이었습니다! 🐾
(추가로 공유하고 싶은 팁이나 경험이 있다면 댓글로 공유해주세요! 여러분의 소중한 경험은 다른 개발자들에게 큰 도움이 됩니다.)

이미지 속 대표 색상을 추출하고 싶을 때는, 이미지 업로드 기반 컬러코드 추출기를 활용해 빠르게 확인할 수 있습니다.









최상의 건강을 위한 영양가득한 식품과 정보! life-plus.co.kr 바로가기
최상의 건강을 위한 영양가득한 식품과 정보! life-plus.co.kr 바로가기



다채로운 문화축제와 공연 소식을 공유하는 블로그! culturestage.co.kr 바로가기
다채로운 문화축제와 공연 소식을 공유하는 블로그! culturestage.co.kr 바로가기



비트코인 세계로의 첫걸음! 지금 가입하고 거래 수수료 할인 혜택 받으세요! bitget.com 바로가기
비트코인 세계로의 첫걸음! 지금 가입하고 거래 수수료 할인 혜택 받으세요! bitget.com 바로가기




Tags

#developer#coding#react

Share

Previous Article
(MySQL/MariaDB) FOREIGN KEY로 테이블 연결하는 완벽 가이드 - 관계형 데이터베이스 설계 기초

Table Of Contents

1
1. 왜 'Cannot read properties of undefined'가 발생할까?
2
2. 실제 프로젝트에서 적용하는 7가지 해결 전략
3
3. 고급 에러 핸들링 기법

Related Posts

React 18의 주요 변화 완벽 가이드 자동 배치, 트랜지션, 동시성 기능까지
December 14, 2025
3 min