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

推荐订阅源

月光博客
月光博客
MyScale Blog
MyScale Blog
博客园 - Franky
The Cloudflare Blog
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
博客园 - 聂微东
WordPress大学
WordPress大学
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
The Blog of Author Tim Ferriss
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
罗磊的独立博客
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
Martin Fowler
Martin Fowler
aimingoo的专栏
aimingoo的专栏
J
Java Code Geeks
腾讯CDC
雷峰网
雷峰网
Microsoft Azure Blog
Microsoft Azure Blog
G
Google Developers Blog
博客园 - 【当耐特】
美团技术团队
云风的 BLOG
云风的 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 ~The best practice for conditional statement~
Ogasawara Kakeru · 2026-06-26 · via DEV Community
Cover image for React.js ~The best practice for conditional statement~

Ogasawara Kakeru

We tend to write React as functional programming because the functional component is the mainstream.
In this era, one of the issues we often encounter is conditional statements. There are a variety of conditional statements, such as if, switch, and ternary operator.
We confuse when to use them properly.

Assign the result of the conditional statement into a variable
This makes it easy to read, test, and modify codebases.

The representative case is ternary operator

const userName = user ? user.name : 'No user found';

Of course, we can write the code another way.

const point = 80;
let result;

if (point >= 70) {
  result = 'passed';
} else {
  result = 'failed';
}

console.log(result);
// passed

In this way, we can not ensure the immutability of let, and this section with the conditional branch is written in a procedural style.

To solve this issue, we have to wrap this in a function.

const judge = (point: number) => {
  if (point >= 70) {
    return 'passed';
  }

  return 'failed';
};

In addition to wrapping that statement,
I suggest that you use early return to save the else statement.

Do not write conditional statements in the return value of tsx (the UI rendering portion)

** When there is only a single conditional statement, or there is no need for any execution in the conditional statement.

Let's use the ternary operation simply.

import { FC } from 'react';
import { useQuery } from '@tanstack/react-query';
import getUser from 'domains/getUser';

type Props = {
  userId: number;
};

const Profile: FC<Props> = (props) => {
  const { userId } = props;
  const getSpecificUser = async () => {
    const specificUser = await getUser(userId);

    return specificUser;
  };
  const { data: user } = useQuery(['user', userId], getSpecificUser);

  const userName = user ? user.name : 'User not found';

  return <p>User{userName}</p>;
};

export default Profile;


const userName = user ? user.name : 'User not found';

In this statement, you only have to watch user, and you don't have any other execution.

Avoid writing this code in the <p> tag.

return <p>User{user ? user.name : 'User not found'}</p>;

This code is unreadable. And this makes JSx complex to understand.
You have to separate logic from UI.

If conditional statements are later or more than 3 statements.
In this case, you had better use ifstatement.

/* eslint-disable no-nested-ternary */
import { FC } from 'react';
import { useQuery } from '@tanstack/react-query';
import getUser from 'domains/getUser';

type Props = {
  userId: number;
};

const Profile: FC<Props> = (props) => {
  const { userId } = props;
  const getSpecificUser = async () => {
    const specificUser = await getUser(userId);

    return specificUser;
  };
  const { data: user } = useQuery(['user', userId], getSpecificUser);

  const userName = user ? user.name : 'User not found';
  const genderColor = user ? (user.gender === 'male ? 'blue' : 'pink') : '';

  return <p className={genderColor}>User:{userName}</p>;
};

export default Profile;

It is unreadable if you write the ternary operator.
In this case, you had better wrap two layers of statements.

import { FC } from 'react';
import { useQuery } from '@tanstack/react-query';
import getUser from 'domains/getUser';

type Props = {
  userId: number;
};

const Profile: FC<Props> = (props) => {
  const { userId } = props;
  const getSpecificUser = async () => {
    const specificUser = await getUser(userId);

    return specificUser;
  };
  const { data: user } = useQuery(['user', userId], getSpecificUser);

  const userName = user ? user.name : 'User not found';
  const genderColor = () => {
    if (!user) {
      return '';
    }

    if (user.gender === 'male') {
      return 'blue';
    }

    return 'pink';
  };

  return <p className={genderColor()}>User{userName}</p>;
};

export default Profile;

You can execute conditional statements within genderColor
In fact, you don't have to write code as a nest with return.
This is another merit of extracting a responsibility from the codebase.

When you want to display another UI
You should switch UI with if statement.

import { FC } from 'react';
import { useQuery } from '@tanstack/react-query';
import getUser from 'domains/getUser';

type Props = {
  userId: number;
};

const Profile: FC<Props> = (props) => {
  const { userId } = props;
  const getSpecificUser = async () => {
    const specificUser = await getUser(userId);

    return specificUser;
  };
  const { data: user } = useQuery(['user', userId], getSpecificUser);

  if (!user) {
    return <p>User notfound</p>;
  }

  const { name, gender, age } = user;
  const genderColor = gender === 'male' ? 'blue' : 'pink';

  return (
    <div className={genderColor}>
      <p>User{name}</p>
      <p>Sex{gender}</p>
      <p>Age{age}</p>
    </div>
  );
};

export default Profile;

You can define UI that is displayed if user is undefined.