이 글은 Qitta에 등록된 JNJDUNK님의 글인 【コード品質】綺麗なReactコード 中級 7例을 번역한 것입니다
기본 : 몇 줄 만으로 아름다운 코딩이 가능할 것
const userInfo = {
username: 'Jnjdunk',
address: 'Tokyo',
favorite: 'Travel',
};
// NG
const username = userInfo.username;
const address = userInfo.address;
const favorite = userInfo.favorite;
// 🥴 Good
const { username, address, favorite } = userInfo;
// NG
const profile = {
username: username,
address: address,
favorite: favorite,
age: 88,
};
// 🥴 Good
// 처음에 변수만을 기술하고 값을 가진 property는 마지막에 기술
const profile = {
username,
address,
favorite,
age: 88,
};
// 😎 Best
const age = 88;
const profile = {
...userInfo,
age,
};
!!! 어디까지나 아름답다는 관점에서
// NG 클래스형 컴포넌트
class UserArea extends React.Component {
render() {
return <h1>Hello, {this.props.username}</h1>;
}
}
// 🥴 Good 함수형 컴포넌트
const UserArea = (props) => {
return <h1>Hello, {props.username}</h1>;
};
억지로 하나의 useEffect
안에 코딩할 필요는 없다
// NG
useEffect(() => {
const getApi1 = async () => {
const response = await api('classinfo');
func1(response);
};
const getApi2 = async () => {
const response = await api('userinfo');
func2(response);
func3(response);
};
getApi1();
getApi2();
}, []);
// 🥴 Good
// 첫 번째
useEffect(() => {
const getApi = async () => {
const response = await api('classinfo');
func1(response);
};
getApi();
}, []);
// 두 번째
useEffect(() => {
const getApi = async () => {
const response = await api('userinfo');
func2(response);
func3(response);
};
getApi();
}, []);
// NG
// 실수하기 쉽다
const [userId, setUserId] = useState();
const [userName, setUserName] = useState();
const [userAddress, setUserAddress] = useState();
const [userFavorite, setUserFavorite] = useState();
setUserId(props.userInfo.userid);
setUserName(props.userInfo.username);
setUserAddress(props.userInfo.address);
setUserFavorite(props.userInfo.favorite);
// 🥴 Good
const [userInfo, setUserInfo] = useState();
setUserInfo(props.userInfo);
// 😎 특정 키에 값을 대입할 때
const favorite = 'Eating';
setUserInfo((prevUserInfo) => ({ ...prevUserInfo, favorite }))
const userProfile = (props) => (
<Box>
{props.username}
<span>{props.address}</span>
</Box>
);
// 🥴 Good
const userProfile = ({ address, username }) => (
<Box>
{username}
<span>{address}</span>
</Box>
);
useContext, props, redux 각 기능 만으로 앱은 구현할 수 있다.
각각의 특성을 이해하고 사용할 것.
useContext
는 얕고 넓은 계층의 컴포넌트에 적합props
를 사용하고 useContext
는 이용하지 말것/* style.css */
.save_button {
color: white;
background: black;
}
// 작성방법 1
import styles from './style.css';
const buttonArea = () => {
return <Button style={style.save_button}>{text}</Button>;
};
// 작성방법 2
const buttonCn = "save_button";
const buttonArea = () => {
return <Button className={buttonCn}>{text}</Button>;
};
const textStyle = {
display: isAdmin ? 'none' : 'block',
};
const textArea = () => {
return <div style={textStyle}>{text}</div>;
};
외부 컴포넌트 등
return (
<>
<style>
{`
.text {
color: ${props.color};
background: black;
}
`}
</style>
<div className='text'>{text}</div>
</>
);
좋은 코드는 코드 작성법만이 아닙니다
여러 기법들 가운데에서, 프로젝트 안에서의 Style, 데이터 규칙의 통일은은 코드 이해에 매우 중요합니다.
좋은 코드에는 정답이 없다
코드의 아름다움은 "예술적인 관점"에 가깝고, 한 가지 정답이 있는 것이 아닙니다. Materal UI, Next의 공식 문서에서 말하는 것만이 정답이 아니며, 적어도 프로덕트에 맞는 방법으로 유지보수와 이식성을 고려하여 추구하는 것으로 정답에 가까워진다고 생각합니다.