
이 글은 Qitta에 등록된 JNJDUNK님의 글인 【コード品質】綺麗なReactコード 基本7例을 번역한 것입니다
최소한 지켜야할 7가지 예시를 소개합니다.
// NG
const apiUrl = origin + '/api/v2/user/' + userId;
// Good🥴
const apiUrl = `${origin}/api/v2/user/${userId}`;
// NG
if (status == 'ko') {
return <KoreanHeader />;
} else {
return <EnglishHeader />;
}
// Good🥴
return status == 'ko' ? <KoreanHeader /> : <EnglishHeader />;
// NG
import React from 'react';
import { useState } from 'react';
import './style/logo.scss';
import logo from './image/logo.png';
import Button from '@material-ui/core/Button';
import useContext from 'react';
// Good🥴
/* 1단: React, React 프레임워크 계열 */
import React, { useContext, useState } from 'react';
/* 2단: UI 프레임워크 계열, 기타 라이브러리 */
import Button from '@material-ui/core/Button';
/* 3단: 사용자 정의, 내부 라이브러리 */
import './style/logo.scss';
import logo from './image/logo.png';
짧은 코딩은 컴포넌트를 코딩할 때 깔끔하게 정리된다
if (temp) {
text = temp;
} else {
text = 'text가 없습니다';
}
// Good🥴
const text = temp || 'text가 없습니다';
// console.log("출력" || "출력하지 않음");
// console.log(null || "출력");
if (response) {
text = response.text;
}
// Good🥴
const text = response && response.text;
// console.log("출력하지 않음" && "출력");
// console.log(null && "출력하지 않음"); <- 출력 null
// console.log("출력하지 않음" && null); <- 출력 null
// 🤔 3항 이후는 직감적이지 않음
const text = response && reponse.text || 'textは存在しません';
// NG
return (
<Button
onClick={(event) => {
console.log(event.target);
}}
>
Push
</Button>
);
// Good🥴
const displayConsole = (e) => {
console.log("target:", e.target);
};
return <Button onClick={displayConsole}>Push</Button>;
반드시 전부를 지칭하지는 않지만 중복 선언은 최대한 삭제한다
// NG
return (
<>
<Box
style={{
height: '100%',
color: warning,
background: 'black',
}}
>
{text1}
</Box>
<Box
style={{
height: '100%',
color: warning,
background: 'black',
}}
>
{text2}
</Box>
</>
);
// Good🥴
const boxStyle = {
height: '100%',
color: warning,
background: 'black',
};
return (
<>
<Box style={boxStyle} onClick={displayConsole}>
{text1}
</Box>
<Box style={boxStyle} onClick={displayConsole}>
{text2}
</Box>
</>
);
// NG
switch (user.type) {
case user:
return <User />;
case admin:
return <AdminUser />;
case host:
return <HostUser />;
}
// Good🥴
const userView = {
host: <User />,
admin: <AdminUser />,
user: <HostUser />,
};
return userView[user.type];
코드의 완성도를 지나치게 의식하면 산으로 가버립니다.
그러므로 이러한 것들을 강요하는 것이 아니라 팀 내에서 깨닫고 경험을 바탕으로 키워가야하는 것이라고 생각합니다.
세세한 것까지 강요하면 개발자의 적극성이 저하되고 성장의 방해로 이어집니다. 지적할 때는 주관에 따르지 말고 프로덕트에서 볼 때 어째서 그래야 하는지 설명해야 합니다. 끝으로 또 다른 코드 품질 향상에 어떠한 것이 있는지 알려주시면 좋겠습니다.