lukeed / clsx

A tiny (239B) utility for constructing `className` strings conditionally.
MIT License
8.08k stars 141 forks source link

Performance question #84

Closed lokomass closed 8 months ago

lokomass commented 9 months ago

Hi. Is it a good practice to use clsx even if I have only one conditionnaly class ?

Exemple

Insteaf of this :

const class = (condition) ? 'Myclass' : undefined
<div className={class}/>

I prefer this approach:

<div className={clsx(
{
'Myclass': condition
}
)}/>

But in term of performance, is there any impact ?

Thanks for replay

drwpow commented 9 months ago

But in term of performance, is there any impact ?

Technically-speaking, yes. The former has (virtually) no execution time. Whereas clsx does have some runtime cost. However, the code you provided runs at ~48M ops/s on my machine. So for all intents and purposes, it’s negligible perf-wise. If it provides clarity in the code even for one class, it’s worth it.

And you have multiple classnames to evaluate, chances are clsx() will be faster than any custom code written.

ivanabovin commented 8 months ago

One more option - clsx(condition && 'MyClass')

lukeed commented 8 months ago

Thanks @drwpow; PS 👋 !!