function ContactList({ contacts }) { return ( <div> <ul> {contacts.length && contacts.map((contact) => ( <li key={contact.id}> {contact.firstName} {contact.lastName} </li> ))} </ul> </div> )}contacts가 []라면 위 코드는 어떻게 될까요? 맞습니다! 0이 렌더링될 것입니다!

0 && anything을 평가할 때, 0은 거짓(falsy)이므로 결과는 항상 0이 되며, &&의 오른쪽은 평가조차 하지 않기 때문입니다.null을 사용하는 것이 완벽합니다.function ContactList({ contacts }) { return ( <div> <ul> {contacts.length ? contacts.map((contact) => ( <li key={contact.id}> {contact.firstName} {contact.lastName} </li> )) : null} </ul> </div> )}function Error({ error }) { return error && <div className="fancy-error">{error.message}</div>}error가 undefined라면 어떻게 될까요? 그런 경우 다음과 같은 에러가 발생할 것입니다.Uncaught Error: Error(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.react-dom.production.min.js:13 Uncaught Invariant Violation: Minified React error #152; visit https://reactjs.org/docs/error-decoder.html?invariant=152&args[]=f for the full message or use the non-minified dev environment for full errors and additional helpful warnings.undefined && anything은 항상 undefined로 평가된다는 점입니다.&&를 사용하고 있다는 점입니다. 다르게 말하면, 조건부로 인자를 전달하기 위해 &&를 사용하고 있는 것입니다. 기억하세요, JSX는 React.createElement 호출을 위한 단순한 구문적 추상화(Syntactic abstraction)일 뿐입니다. 따라서 이는 다음과 같이 코드를 작성하려는 것과 같습니다.function throwTheCandy(candyNames) { for (const candyName of candyNames) { throwCandy(candyName) }}throwTheCandy(candies.length && candies.map((c) => c.name))0을 렌더링하는 것이 유효하기 때문입니다.undefined를 반환하는 두 번째 예시와 같은 상황을 피하도록 도와줄 수 있습니다. 하지만 그러한 보호 계층을 넘어, 우리의 의도를 좀 더 명확하게 표현해 보는 것은 어떨까요? 무언가를 조건부로 수행하고 싶다면, 논리 AND 연산자(&&)를 남용하지 마세요.if 조건문에서 &&를 사용하여 "이 두 값이 모두 참(truthy)이면 이 일을 수행하고, 그렇지 않으면 하지 마라"는 의미로 사용하기 때문에, 이것이 직관에 어긋나는 것처럼 보일 수 있습니다. 불행히도 우리의 사용 사례에서 && 연산자는 두 값이 모두 참이 아닐 경우 거짓인 쪽의 값을 반환하는 "특징"을 가지고 있습니다.0 && true // 0true && 0 // 0false && true // falsetrue && '' // ''&&(또는 ||)를 남용하기보다는 삼항 연산자(condition ? trueConsequent : falseConsequent)나 심지어 if 문(그리고 미래에는 아마도 do 표현식(do expressions))과 같은 실제 분기 구문 기능을 사용할 것을 강력히 권장합니다. if 문을 더 선호하신다면 그것도 좋습니다. if 문을 사용하여 연락처 목록 예시를 작성하면 다음과 같습니다.function ContactList({ contacts }) { let contactsElements = null if (contacts.length) { contactsElements = contacts.map((contact) => ( <li key={contact.id}> {contact.firstName} {contact.lastName} </li> )) } return ( <div> <ul>{contactsElements}</ul> </div> )}!!contacts.length && ...나 contacts.length > 0 && ..., 또는 Boolean(contacts.length) && ...를 사용하여 연락처 문제를 해결할 수 있다는 것을 잘 알고 있습니다. 하지만 저는 여전히 렌더링을 위해 논리 AND 연산자를 남용하지 않는 것을 선호합니다. 저는 삼항 연산자를 사용하여 명시적으로 표현하는 것을 선호합니다.function ContactList({ contacts }) { return ( <div> <ul> {contacts.length ? contacts.map((contact) => ( <li key={contact.id}> {contact.firstName} {contact.lastName} </li> )) : null} </ul> </div> )}function Error({ error }) { return error ? <div className="fancy-error">{error.message}</div> : null}아직 댓글이 없습니다.
첫 번째 댓글을 작성해보세요!

Claude Code 공식 Plugin 추천 +α (속편)
Inkyu Oh • AI & ML-ops

Claude Code에서 이용 제한에 빨리 걸리지 않게 하는 팁
Inkyu Oh • AI & ML-ops

더 적고, 더 긴 테스트를 작성하세요
Inkyu Oh • Front-End

타입 세이프한 합성 컴포넌트 만들기
Inkyu Oh • Front-End