Skip to content

Instantly share code, notes, and snippets.

@azu
Last active April 11, 2025 04:58
Show Gist options
  • Save azu/0dc07179f66a6471f0a0aa681709b2f5 to your computer and use it in GitHub Desktop.
Save azu/0dc07179f66a6471f0a0aa681709b2f5 to your computer and use it in GitHub Desktop.
export const requireComment = {
meta: {
type: "suggestion",
docs: {
description: "useEffectにはコメントでの説明が必須です。",
},
schema: [],
messages: {
requireCommentOnUseEffect: `useEffectにはコメントでの説明が必須です。
useEffectはReactのパラダイムからのエスケープパッチなので、使うには理由が必要です(できるだけ避けるべきです)。
useEffectで「なにがしたいか」「なぜuseEffectを使うのか」「いつ呼ばれるのか」をコメントで書いてください。
// What: 〜する処理
// Why: 〜と連携するため、effectを使う
// When: 〜の値が変更されたときに呼ばれる(第2引数が空配列 または 複雑な場合は書いてください)
例)
function Form() {
// Formコンポーネントを表示したことを、アクセス解析ツールに記録する処理
// コンポーネントをマウント時に、一度だけ記録する(devだと複数回呼ばれるがdevのみなので問題ない)
useEffect(() => {
post('/analytics/event', { eventName: 'visit_form' });
}, []);
return <form>...</form>;
}
参考:
- そのエフェクトは不要かも: https://ja.react.dev/learn/you-might-not-need-an-effect
- useEffectにはコメントをつけよう: https://www.pandanoir.info/entry/2025/01/29/205439
- コメントには「なぜ」を書く: https://jisou-programmer.beproud.jp/%E9%96%A2%E6%95%B0%E8%A8%AD%E8%A8%88/10-%E3%82%B3%E3%83%A1%E3%83%B3%E3%83%88%E3%81%AB%E3%81%AF%E3%80%8C%E3%81%AA%E3%81%9C%E3%80%8D%E3%82%92%E6%9B%B8%E3%81%8F.html
`,
},
},
create(context) {
return {
CallExpression(node) {
// `useEffect()` の前にコメントがない場合はエラーを出す
if (
node.callee.type === "Identifier" &&
node.callee.name === "useEffect"
) {
const comments = context.getSourceCode().getCommentsBefore(node);
if (comments.length === 0) {
context.report({
node,
messageId: "requireCommentOnUseEffect",
});
}
}
// `React.useEffect()` のコメントがない場合はエラーを出す
if (node.callee.type === "MemberExpression") {
const { object, property } = node.callee;
if (
object.type === "Identifier" &&
object.name === "React" &&
property.type === "Identifier" &&
property.name === "useEffect"
) {
const comments = context.getSourceCode().getCommentsBefore(node);
if (comments.length === 0) {
context.report({
node,
messageId: "requireCommentOnUseEffect",
});
}
}
}
},
};
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment