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

doakuma·2022년 10월 29일
0

CodingConvention

목록 보기
1/4
post-thumbnail

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

들어가며

  • React는 Html이나 JS를 혼동하여 코딩이 가능한 JSX를 사용하기 때문에 다양한 코딩 방식을 적용할수 있다
  • 다양한 코딩 방식이 복잡하게 적용되면 설명, 유지보수가 어려워진다
  • 따라서 최소한 통일된 코딩 규칙을 정해야 한다

최소 전제 조건

  • pretteier이나 formatter의 설정은 개발자들끼리 공유되어 있어야 할 것
  • warning, 예외처리
  • 과도한 console은 없어야할 것
  • 최소한의 코딩 규약은 파악할 것

좋은 코드의 기본

최소한 지켜야할 7가지 예시를 소개합니다.

1. 문자열은 직감적이며 알기 쉽게

// NG
const apiUrl = origin + '/api/v2/user/' + userId;

// Good🥴
const apiUrl = `${origin}/api/v2/user/${userId}`;

2. if의 남용은 행 수를 많이 차지한다

// NG
if (status == 'ko') {
  return <KoreanHeader />;
} else {
  return <EnglishHeader />;
}

// Good🥴
return status == 'ko' ? <KoreanHeader /> : <EnglishHeader />;

3. Import는 규칙을 가지는가

// 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';

4. AND/OR문은 React와 궁합이 좋지만 지나친 사용에는 주의할 것

짧은 코딩은 컴포넌트를 코딩할 때 깔끔하게 정리된다

4-1 OR: 변수에 값이 존재할 때 대입하고 싶은 경우

if (temp) {
  text = temp;
} else {
  text = 'text가 없습니다';
}
// Good🥴
const text = temp || 'text가 없습니다';
// console.log("출력" || "출력하지 않음");
// console.log(null || "출력");

4-2 AND: 변수에 값이 존재하는 지 확인하고 대입하고 싶은 경우

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は存在しません';

5. render 함수 내의 이벤트는 떼어낸다

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

6. style도 적절하게 떼어낸다

반드시 전부를 지칭하지는 않지만 중복 선언은 최대한 삭제한다

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

7. object는 자유롭게 쓸 수 있는가

// 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];

8. UI 라이브러리는 자유롭게 쓸 수 있는가

  • HTML코딩에 너무 의지하지는 않는가
  • 작성된 코드는 사용하는 UI라이브러리로 치환할 수 없는가

중급편

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

상급편

  • api 관련 값을 관리
  • redux
  • style theme
  • 디렉토리 구성

나가며

코드의 완성도를 지나치게 의식하면 산으로 가버립니다.
그러므로 이러한 것들을 강요하는 것이 아니라 팀 내에서 깨닫고 경험을 바탕으로 키워가야하는 것이라고 생각합니다.
세세한 것까지 강요하면 개발자의 적극성이 저하되고 성장의 방해로 이어집니다. 지적할 때는 주관에 따르지 말고 프로덕트에서 볼 때 어째서 그래야 하는지 설명해야 합니다. 끝으로 또 다른 코드 품질 향상에 어떠한 것이 있는지 알려주시면 좋겠습니다.

profile
늦깎이 프론트 개발자

0개의 댓글