[번역][코드품질] 아름다운 React Code 7 (중급)

doakuma·2022년 10월 29일
0

CodingConvention

목록 보기
2/4
post-thumbnail

이 글은 Qitta에 등록된 JNJDUNK님의 글인 【コード品質】綺麗なReactコード 中級 7例을 번역한 것입니다

들어가며

  • React에는 많은 데이터를 유지 및 변경을 통해 동적으로 컴포넌트를 표현한다
  • 데이터를 주고받고, 대입 및 유지는 React만의 방법으로 이루어진다

전제

기본 : 몇 줄 만으로 아름다운 코딩이 가능할 것


1. value 전달이 간결한가

1-1. value 전달 : 한번에 모아서 전달

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;

1-2. 대입 : 프로퍼티 값을 생략하여 사용하고 있는가

// 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,
};

2. 함수형 컴포넌트가 가독성이 높다

!!! 어디까지나 아름답다는 관점에서

// NG 클래스형 컴포넌트
class UserArea extends React.Component {
  render() {
    return <h1>Hello, {this.props.username}</h1>;
  }
}

// 🥴 Good 함수형 컴포넌트
const UserArea = (props) => {
  return <h1>Hello, {props.username}</h1>;
};

3. useEffect는 여러 개 사용해도 된다

억지로 하나의 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();
}, []);

4. 최소한의 useState로 데이터 전달

// 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 }))

5. 사용하는 Props의 값의 가시화

const userProfile = (props) => (
  <Box>
    {props.username}
    <span>{props.address}</span>
  </Box>
);

// 🥴 Good
const userProfile = ({ address, username }) => (
  <Box>
    {username}
    <span>{address}</span>
  </Box>
);

6. 데이터 유지는 방법대로 사용하고 있는가

useContext, props, redux 각 기능 만으로 앱은 구현할 수 있다.
각각의 특성을 이해하고 사용할 것.

규칙 예시

  1. useContext는 얕고 넓은 계층의 컴포넌트에 적합
    • default style
    • Header, Footer
    • 특정 상태, on/off
  2. 독립된 컴포넌트에는 props를 사용하고 useContext는 이용하지 말것
    • 의존관계가 부모의 값만 갖게 된다
    • 재사용이 간단해진다
  3. 복잡한 데이터 변경 패턴이 많은 경우 Redux를 사용한다

7. Style 사용법은 구분되어 있는가

  • 한 가지 방법으로는 스타일링이 어렵다
  • Style의 사용은 명기되어야 한다

7-1. CSS Module : 기본은 CSS/SCSS 베이스로 디자인

/* 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>;
};

7-2. Inline CSS : 일부 동적 변경

const textStyle = {
  display: isAdmin ? 'none' : 'block',
};
const textArea = () => {
  return <div style={textStyle}>{text}</div>;
};

7-3. CSS In Js : 변경되지 않는 클래스명의 스타일을 동적으로 변경하고 싶을 때

외부 컴포넌트 등

  return (
    <>
      <style>
        {`
        .text {
            color: ${props.color};
            background: black;
        }
        `}
      </style>
      <div className='text'>{text}</div>
    </>
  );

나가며

좋은 코드는 코드 작성법만이 아닙니다
여러 기법들 가운데에서, 프로젝트 안에서의 Style, 데이터 규칙의 통일은은 코드 이해에 매우 중요합니다.
좋은 코드에는 정답이 없다
코드의 아름다움은 "예술적인 관점"에 가깝고, 한 가지 정답이 있는 것이 아닙니다. Materal UI, Next의 공식 문서에서 말하는 것만이 정답이 아니며, 적어도 프로덕트에 맞는 방법으로 유지보수와 이식성을 고려하여 추구하는 것으로 정답에 가까워진다고 생각합니다.

profile
늦깎이 프론트 개발자

0개의 댓글