惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
Martin Fowler
Martin Fowler
Vercel News
Vercel News
U
Unit 42
Engineering at Meta
Engineering at Meta
aimingoo的专栏
aimingoo的专栏
MyScale Blog
MyScale Blog
Y
Y Combinator Blog
阮一峰的网络日志
阮一峰的网络日志
爱范儿
爱范儿
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
B
Blog RSS Feed
N
Netflix TechBlog - Medium
GbyAI
GbyAI
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
大猫的无限游戏
大猫的无限游戏
C
Check Point Blog
M
MIT News - Artificial intelligence
D
Docker
IT之家
IT之家
Stack Overflow Blog
Stack Overflow Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
React.js ~Clean Code Practical Use~
Ogasawara Kakeru · 2026-06-14 · via DEV Community
Cover image for React.js ~Clean Code Practical Use~

Ogasawara Kakeru

1. The codebase should be created for concentrating on <>JSX Section</>

-The JSX section can often be modified after release.

  • Separate a data-fetching section from the view section.
// NG🤔 You can not comprehend the important point intuitively.
const Area = () => {
  const [user, setUser] = useState();

  useEffect(() => {
    const fetchUser = async (): Promise<void> => {
      const response = await GetUser();
      setUser(response);
    };
    fetchUser();
  }, []);

  return <>{user.name}</>;
};

// Good😎 Separate a data-fetching section from the view section.
const useUser = (): User | undefined => {
  const [user, setUser] = useState<User>();
  useEffect(() => {
    const fetchUser = async (): Promise<void> => {
      const response = await GetUser();
      setUser(response);
    };
    fetchUser();
  }, []);

  return user;
};

// A component for showing data.
const Area = () => {
  const user = useUser();

  return <>{user?.name}</>;
};

2. Don't use too many useState for data-input

// NG🤔 What is going to happen if the `input` element continues to increase...
const UserForm = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  const changeName = (e) => setName(e.target.value);
  const changeEmail = (e) => setEmail(e.target.value);

  return (
    <form onSubmit={onSubmit}>
      <input type='text' value={name} onChange={changeName} />
      <input type='text' value={email} onChange={changeEmail} />
      <input type='submit' value='Submit' />
    </form>
  );
};

// Good😎 Manage submit data in a user object.
const UserForm = () => {
  const [user, setUser] = useState({ name: '', email: '' });

  const changeName = (e) =>
    setUser((state) => ({ ...user, name: e.target.value }));

  const changeEmail = (e) =>
    setUser((state) => ({ ...user, email: e.target.value }));

  return (
    <form onSubmit={onSubmit}>
      <input type='text' value={name} onChange={changeName} />
      <input type='text' value={email} onChange={changeEmail} />
      <input type='submit' value='Submit' />
    </form>
  );
};

// Cool😎: Take advantage of useForm
const UserForm = () => {
   const { register} = useForm();

  return (
    <form onSubmit={onSubmit}>
      <input {...register("name")} />
      <input {...register("email")} />
      <input type='submit' value='Submit' />
    </form>
  );
};

3. Insert a default value to an optional one

type Props = {
  name: string;
  isDisplayNone?: boolean; // An optional props
};

// NG🤔: Defined as isDisplayNone = undefined
const UserCard: FC<Props> = ({ name, isDisplayNone }) => (
  <div style={{ display: isDisplayNone ? 'none' : 'block' }}>{name}</div>
);

// Good😎: Defined as isDisplayNone = false 
const UserCard: FC<Props> = ({ name, isDisplayNone = false }) => (
  <div style={{ display: isDisplayNone ? 'none' : 'block' }}>{name}</div>
);

// When showing isDisplayNone undefined -> false
<UserCard name='名前' />;
// When not showing isDisplayNone true
<UserCard name='名前' isDisplayNone />;

4. Pay attention to import statement

/* NG🤔
├── Layout
    ├── Header.tsx
    └── Footer.tsx
*/
// page.tsx import files separately
import Header from './Layout/Header';
import Footer from './Layout/Footer';

/* Good🥴
├── Layout
    ├── Header.tsx
    ├── Footer.tsx
    └── index.tsx
*/
// index.tsx
export { default as Header } from './Header';
export { default as Footer } from './Footer';

// page.tsx import as a chunk
import { Footer, Header } from './Layout';

Allow importing from the same path everywhere.

// NG:
import { Footer, Header } from '../../../../Layout';

// Good:😎
import { Footer, Header } from '@components/Layout';

5. Make use of array methods

const data = [1,2,10]
const isIncludedNumber2 = data.includes(2);
const isIncludedNumber2Or3 = data.some((item) => item === 2 || item === 3);
const number3= data.find((item) => item === 3);
const numbersLargerThan2 = data.filter((item) => item > 2);
const totalNumber = data.reduce((sum, num) => sum + num, 0);

6. Centerize how to manage unique values of the service

  • If values defined specifically for the service are written directly into the code, it becomes difficult to understand.
  • Is the code written in a way that prevents misunderstandings?
// NG🤔 status: What does the 0 mean?
const CheckStatus = (status: number) => {
  if (status === 0) {
    return true;
  }
  return false;
};

// Good🥴
const Status = {
  Invalid: 0,
  Valid: 1,
} as const;

type StatusLiteral = typeof Status[keyof typeof Status]; // 0 | 1

const CheckStatus = (status: StatusLiteral) => {
  if (status === Status.Invalid) {
    return true;
  }
  return false;
};