LoginSignup
883
886

More than 1 year has passed since last update.

クリーンなReactプロジェクトの21のベストプラクティス

Last updated at Posted at 2021-09-19

本記事は、Mohammad Faisal氏による「21 Best Practices for a Clean React Project」(2021年4月23日公開)の和訳を、著者の許可を得て掲載しているものです。

クリーンなReactプロジェクトの21のベストプラクティス

コード品質向上のための実践的アドバイス

Woman with index finger over mouth
Photo by Diana Polekhina on Unsplash.

はじめに

Reactは、構成の方法について特に決まりがありません。まさにこれが理由で、プロジェクトをクリーンで保守可能な状態に保つことは、私たちの責任なのです。

今日は、Reactアプリケーションの状態を改善するために従うべきベストプラクティスについて説明します。これらのルールは広く受け入れられているため、この知識を持つことは必須です。

すべてコードで示します。さあ始めましょう!

1. JSXの省略形を使用する

ブール変数の受け渡しには、JSXの省略形を使うようにしましょう。例えば、Navbarコンポーネントのタイトルの可視性を制御するとします。

悪い例

return (
    <Navbar showTitle={true} />
);

shorthand-bad.jsx

良い例

return(
    <Navbar showTitle />
)

shorthand-good.jsx

2. 三項演算子を使用する

例えば、ロールに基づいて特定のユーザーの詳細を表示するとします。

悪い例

const { role } = user;
if(role === ADMIN) {
    return <AdminUser />
}else{
    return <NormalUser />
}

ternary-bad.jsx

良い例

const { role } = user;
return role === ADMIN ? <AdminUser /> : <NormalUser />

ternary-good.jsx

3. オブジェクトリテラルを活用する

オブジェクトリテラルは、コードを読みやすくするのに役立ちます。例えば、役割に応じて3種類のユーザーを表示するとします。選択肢の数が3つ以上なので、三項演算子は使えません。

悪い例

const {role} = user
switch(role){
    case ADMIN:
        return <AdminUser />
    case EMPLOYEE:
        return <EmployeeUser />
    case USER:
        return <NormalUser />
}

conditional-rendering-bad.jsx

良い例

const {role} = user
const components = {
    ADMIN: AdminUser,
    EMPLOYEE: EmployeeUser,
    USER: NormalUser
};

const Component = components[role];
return <Componenent />;

conditional-rendering-good.jsx

これでかなり見やすくなりました。

4. フラグメントを使用する

常にdivよりもFragmentを使うようにしましょう。コードをクリーンに保ち、仮想DOMに作成されるノードが1つ減るため、パフォーマンスにも役立ちます。

悪い例

return (
    <div>
        <Component1 />
        <Component2 />
        <Component3 />
    </div>
)

fragment-bad.jsx

良い例

return (
    <>
        <Component1 />
        <Component2 />
        <Component3 />
    </>
)

fragment-good.jsx

5. レンダー内で関数を定義しない

レンダー内で関数を定義しないようにしましょう。レンダー内のロジックは最小限に抑えるようにしてください。

悪い例

return (
    <button onClick={() => dispatch(ACTION_TO_SEND_DATA)}> // NOTICE HERE
        This is a bad example
    </button>
)

function-render-bad.jsx

良い例

const submitData = () => dispatch(ACTION_TO_SEND_DATA)

return (
    <button onClick={submitData}>
        This is a good example
    </button>
)

function-render-good.js

6. メモを使用する

React.PureComponentmemoは、アプリケーションのパフォーマンスを大幅に向上させます。不必要なレンダリングを回避できます。

悪い例

import React, { useState } from "react";

export const TestMemo = () => {
    const [userName, setUserName] = useState("faisal");
    const [count, setCount] = useState(0);
    const increment = () => setCount((count) => count + 1);
    return (
        <>
            <ChildrenComponent userName={userName} />
            <button onClick={increment}> Increment </button>
        </>
    );
};

const ChildrenComponent =({ userName }) => {
    console.log("rendered", userName);
    return <div> {userName} </div>;
};

memo-bad.jsx

countの値はChildComponentとは関係がないため、子コンポーネントは1回だけレンダリングする必要があります。しかし、ボタンをクリックするたびにレンダリングされてしまいます。

Output

良い例

ChildrenComponentを次のように編集しましょう。

import React ,{useState} from "react";

const ChildrenComponent = React.memo(({userName}) => {
    console.log('rendered')
    return <div> {userName}</div>
})

memo-good.jsx

これでボタンを何回クリックしても、必要な時だけレンダリングされるようになりました。

7. CSSをJavaScriptに入れる

CSSの整理はJSの整理よりもはるかに難しいため、Reactアプリケーションを作成する時は、生のJavaScriptを避けるようにしましょう。

悪い例

// CSS FILE
.body {
    height: 10px;
}

//JSX
return <div className='body'>
</div>

css-bad.jsx

良い例

const bodyStyle = {
    height: "10px"
}
return <div style={bodyStyle}>
</div>

css-good.jsx

8. オブジェクト分割代入を使用する

オブジェクト分割代入を活用しましょう。例えば、ユーザーの詳細を表示する必要があるとします。

悪い例

return (
    <>
        <div> {user.name} </div>
        <div> {user.age} </div>
        <div> {user.profession} </div>
    </>
)

descrutcure-bad.jsx

良い例

const { name, age, profession } = user;

return (
    <>
        <div> {name} </div>
        <div> {age} </div>
        <div> {profession} </div>
    </>
)

descructuring-good.jsx

9. 文字列属性に波括弧は不要

例えば、文字列属性を子コンポーネントに渡すとします。

悪い例

return(
    <Navbar title={"My Special App"} />
)

string-props.-bad.jsx

良い例

return(
    <Navbar title="My Special App" />
)

string-prop-good.jsx

10. JSXからJSコードを削除する

レンダリングやUI機能に役立たないJSコードは、JSX外に移動させましょう。

悪い例

return (
    <ul>
        {posts.map((post) => (
            <li onClick={event => {
                console.log(event.target, 'clicked!'); // <- THIS IS BAD
                }} key={post.id}>{post.title}
            </li>
        ))}
    </ul>
);

js-in-jsx-bad.jsx

良い例

const onClickHandler = (event) => {
    console.log(event.target, 'clicked!');
}
return (
    <ul>
        {posts.map((post) => (
            <li onClick={onClickHandler} key={post.id}> {post.title} </li>
        ))}
    </ul>
);

jsx-in-js-good.jsx

11. テンプレートリテラルを使用する

大きな文字列を作るには、テンプレートリテラルを使いましょう。文字列の連結は避けてください。素晴らしくてクリーンです。

悪い例

const userDetails = user.name + "'s profession is" + user.proffession
return (
    <div> {userDetails} </div>
)

concatention-bad.jsx

良い例

const userDetails = `${user.name}'s profession is ${user.proffession}`
return (
    <div> {userDetails} </div>
)

cancatention-good.jsx

12. 順番にインポートする

常に特定の順序でインポートしましょう。コードの可読性が向上します。

悪い例

import React from 'react';
import ErrorImg from '../../assets/images/error.png';
import styled from 'styled-components/native';
import colors from '../../styles/colors';
import { PropTypes } from 'prop-types';

import-bad.jsx

良い例

インポートの順番はこのようにするのが鉄則です。

  • ビルトイン
  • 外部
  • 内部

つまり、上の例は次のようになります。

import React from 'react';

import { PropTypes } from 'prop-types';
import styled from 'styled-components/native';

import ErrorImg from '../../assets/images/error.png';
import colors from '../../styles/colors';

import-good.jsx

13. 暗黙の戻り値を使用する

JavaScriptの機能である暗黙の戻り値を使って、美しいコードを書きましょう。例えば、関数が単純な計算をして、その結果を返すとします。

悪い例

const add = (a, b) => {
    return a + b;
}

implicit-return-bad.js

良い例

const add = (a, b) => a + b;

implicit-return-good.js

14. コンポーネントの命名

コンポーネントにはパスカルケース、インスタンスにはキャメルケースを使いましょう。

悪い例

import reservationCard from './ReservationCard';
const ReservationItem = <ReservationCard />;

naming-component-bad.jsx

良い例

import ReservationCard from './ReservationCard';
const reservationItem = <ReservationCard />;

naming-good.jsx

15. 予約済み属性の命名

コンポーネント間の属性の受け渡しに DOMコンポーネントの属性名を使わないようにしましょう。

悪い例

<MyComponent style="dark" />
<MyComponent className="dark" />

prop-naming-bad.jsx

良い例

<MyComponent variant="fancy" />

prop-naming-good.jsx

16. 引用符

JSX の属性には二重引用符を使い、その他の JS には一重引用符を使います。

悪い例

<Foo bar='bar' />
<Foo style={{ left: "20px" }} />

quotes-bad.jsx

良い例

<Foo bar="bar" />
<Foo style={{ left: '20px' }} />

quotes-good.jsx

17. 属性の命名

属性名には常にキャメルケースを、属性値がReactコンポーネントの場合はパスカルケースを使いましょう。

悪い例

<Component
    UserName="hello"
    phone_number={12345678}
/>

prop-naming-bad.jsx

良い例

<MyComponent
    userName="hello"
    phoneNumber={12345678}
    Component={SomeComponent}
/>

prop-name-good.jsx

18. 括弧内のJSX

コンポーネントが複数行にわたる場合は、必ず括弧で囲みましょう。

悪い例

return <MyComponent variant="long">
            <MyChild />
        </MyComponent>;

jsx-bad.jsx

良い例

return (
    <MyComponent variant="long">
        <MyChild />
    </MyComponent>
);

jsx-good.jsx

19. 自己終了タグ

コンポーネントに子要素がない場合は、自己終了タグを使いましょう。可読性が向上します。

悪い例

<SomeComponent variant="stuff"></SomeComponent>

self-closing-bad.jsx

良い例

<SomeComponent variant="stuff" />

self-closing-good.jsx

20. メソッド名のアンダースコア

Reactの内部メソッドではアンダースコアを使わないようにしましょう。

悪い例

const _onClickHandler = () => {
    // do stuff
}

underscore-bad.jsx

良い例

const onClickHandler = () => {
    // do stuff
}

underscore-good.jsx

21. alt属性

<img>タグには必ず alt属性を入れましょう。スクリーンリーダーはすでにimg要素を画像として認識しているため、alt属性にpictureimageを使わないでください。その必要はありません。

悪い例

<img src="hello.jpg" />
<img src="hello.jpg" alt="Picture of me rowing a boat" />

alt-bad.jsx

良い例

<img src="hello.jpg" alt="Me waving hello" />

alt-good.jsx

おわりに

これで終了です。ここまで読んだ方に、拍手を送ります!この記事から何かを学んでいただけたら嬉しいです。良い一日を!:D

何かありましたら、ぜひLinkedInでご連絡ください。

Reactの16の問題を解決する45のNPMパッケージ
完璧なnpmパッケージの選び方を徹底解説
javascript.plainenglish.io

圧倒的に速いReactJSアプリケーションのトップライブラリ7選
凄腕デベロッパーの必携ツール
betterprogramming.pub

API設計スキルを次のレベルに引き上げる22のベストプラクティス
REST APIを設計するための実践的アドバイス
betterprogramming.pub

大規模Reactアプリに欠かせない20の必須項目
企業レベルのコードを作成しているなら、これを知っておく必要があります
javascript.plainenglish.io

リソース

Anupam Chughに謝意を表します。

翻訳協力

この記事は以下の方々のご協力により公開する事ができました。改めて感謝致します。

Original Author: Mohammad Faisal (Linkedin)
Original Article: 21 Best Practices for a Clean React Project
Thank you for letting us share your knowledge!

選定担当: @gracen
翻訳担当: @gracen
監査担当: -
公開担当: @gracen

こちらもどうぞ
すごいReactパッケージ5選
すごいReactフック8選

ご意見・ご感想をお待ちしております

今回の記事はいかがでしたか?
・こういう記事が読みたい
・こういうところが良かった
・こうした方が良いのではないか
などなど、率直なご意見を募集しております。
頂いたお声は、今後の記事の質向上に役立たせて頂きますので、お気軽に
コメント欄にてご投稿ください。Twitterでもご意見を受け付けております。
皆様のメッセージをお待ちしております。

883
886
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
883
886