Zum Hauptinhalt springen
Intelligence View
⚡ tsecurity.de Intelligence

React.js ~The best practice for conditional statement~

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…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Quelle & Fakten · 4 Min. Lesezeit
Quelle: dev.to
Rubrik: Sichere Programmierung

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.

Social ReaktionenReagiere als Erste:r — dein Feedback zählt!
Informations-Bewertung:
✏️ Information ergänzen
🛡️ Versioniert via CMS-Revisions-Engine (Freigabe-Queue für Gäste)

💬 Topluluk tartışması ve yorumlar

🌐 Ana sohbete katıl

Tartışmayı başlat: Social Chat yayın akışı veya yukarıdaki ekleme formuyla uzman katkısı gönder.

Security Briefing Ücretsiz · Tek tıkla abonelikten çıkma

Zeka Digest - ücretsiz

Günlük en önemli güvenlik haberi · herhangi bir zamanda alınabilir

Community Rating &amp; Social Proof
⭐ Okuyucu Puanı
–
Ø / 5.0
Hiçbir okuyucu henüz yorum yok
Bu makale yararlı mıydı?
0
Değerlendirmenizi gönderin
Detaylı değerlendirme (isteğe bağlı)
İçerik ve Kalite
Kaynak ve Güvenilirlik
Güncellik

İlgili Story Cluster & Kaynaklar (vector AI)

6 Cluster
28 Kaynaklar
GOG Black Friday sale is live, plus multiple Lara Croft games enter the GOG Preservation Program
GamingOnLinux Latest Articles 39 dakika önce
27 diğer kaynaklar
Latest from TechRadar54 dakika önceBlack Friday Sonos: the best deals on wireless speakers, soundbars and more Latest from TechRadar48 dakika önceBlack Friday discounts on Seagate's Expansion Desktop Hard Drive make it one of the cheapest of its kind, with discounts of up to 22% on higher storage capacities Latest from TechRadar44 dakika önceThe best Black Friday Philips Hue deals: save on smart bulbs, string lights, and light strips Latest from TechRadar42 dakika önceNewegg knocks $348 off its AMD Ryzen 7 5800X3D PC bundle for Black Friday Latest from TechRadar41 dakika önceThe best early Black Friday Garmin deals, picked by a smartwatch tester Latest from TechRadar31 dakika önceWork like it's 1998: Aura Displays' retro-inspired Bondi Blue Triple Aero ’98 Pro Max laptop screen extender gets a 16% discount for Black Friday Latest from TechRadar31 dakika önceThe Disney+ and Hulu Black Friday streaming deal for just $5 has returned Golem.de40 dakika önceAnzeige: Beliebter WLAN-Repeater für nur 23,32 Euro im Black Friday Angebot Android51 dakika önceBose Black Friday: Diese Kopfhörer, Soundbars und Boxen sind heute reduziert Latest from TechRadar1 saat önceBlack Friday phone deals: 35 hand-picked deals on Apple iPhones, Pixels, Samsung phones, and more PC-WELT58 dakika önceBlack Friday: Saugroboter von Dyson, Roborock und Mova heute zum Amazon-Tiefstpreis PC-WELT58 dakika önceBlack Friday: Saugroboter von Dyson, Roborock und Mova heute zum Amazon-Tiefstpreis Latest from TechRadar1 saat önceApple's lightweight 2026 M5 MacBook Air gets $250 off for Black Friday Engadget1 saat önceFive solar generators going for deep discounts on Black Friday The Verge1 saat önceXteink’s pocketable X4 Classic e-reader is down to just $55 for Black Friday PC-WELT1 saat önceMein liebstes Produktivitäts-Gadget: Stream Deck zum Black Friday günstiger PC-WELT1 saat önceApple Mac mini wird immer günstiger: Diese Mini-PCs sind im Black-Friday-Sale PC-WELT1 saat önceMein liebstes Produktivitäts-Gadget: Stream Deck zum Black Friday günstiger Codrops2 gün önceBlack Friday 2026: 10 Deals for Web Designers and Front-End Developers CNET12 gün önceSave $112 on Sony’s Flagship WH-1000XM6 Headphones This Black Friday CNET1 saat önceSave $56 on Baseus Inspire XC1 Open Earbuds With This Black Friday Deal Golem.de1 saat önceAnzeige: Ankers Soundcore-Lautsprecher zum Black Friday für 18 Euro bei Amazon PC-WELT2 saat önceBlack Friday: MacBook, Surface & Co. jetzt bis zu 630 Euro günstiger Latest from TechRadar1 saat önceThousands of Black Friday deals are live right now. These are the 175 best Latest from Windows Central2 saat önceXBOX 25th anniversary hardware has a perfect companion for mobile gaming — and it's 20% off for Black Friday PC-WELT1 saat önceDas beste Tool, das ich je für unter 14 Euro gekauft habe – jetzt als Black-Friday-Schnäppchen CNET2 saat önceShop Top Apple Watch Black Friday Deals, Starting at $179
3 Kaynaklar
Twilio's New 10DLC Rejection Codes (Dec 2026): What Each Means and How to Avoid Paying for a Rejection
DEV Community 28 dakika önce
2 diğer kaynaklar
Benzer katkılar
🔍 Verwandte News

Auch interessante Nachrichten React.js ~The best practice for conditional statement~

Thematisch verwandte Begriffe: Reactjs, best, practice, conditional · 6 Treffer

Laden...

Contributions yüklenir ...

Laden...

Videolar yükleniyor...

Laden...

Contributions yüklenir ...

Laden...

Videolar yükleniyor...

Laden...

Contributions yüklenir ...

Laden...

Videolar yükleniyor...

Laden...

Contributions yüklenir ...

Laden...

Videolar yükleniyor...

Yorumlar yüklenir..
Update to Update
Widgets & Topics
Loading widgets…
Nächster Beitrag