lukeed/clsx

Performance question

lokomass opened this issue · 3 comments

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

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.

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

lukeed commented

Thanks @drwpow; PS 👋 !!