DEV Community

Cover image for Little React productivity boost by 'curried' function
Humoyun Ahmad
Humoyun Ahmad

Posted on β€’ Edited on

5 2 1

Little React productivity boost by 'curried' function

Assalom alaykum!

React da ko'pincha ushbu holatdagi event handler larni ishlatilishini guvohi bo'lamiz ya'ni odatda implicit bo'lgan dastlabki event argumentimizga qo'shimcha tarzda 2 - argumentni ham funksiyamizga yuborishga to'g'ri keladi:

const handleChange = (e: Event, type: string) => {
  // input event va type bilan bog'liq kodimiz
}

return (
  <>
    <!-- ... -->
    <input onChange={(e) => handleChange(e, 'line')} />
    <!-- ... -->
    <input onChange={(e) => handleChange(e, 'point')} />
    <!-- ... -->
    <input onChange={(e) => handleChange(e, 'polygon')} />
    <!-- ... -->
  </>
)
Enter fullscreen mode Exit fullscreen mode

Ushbu kod albatta xatosiz ishlaydi lekin bu yerda muammo onChange event handler funksiyamizni yoyishga to'g'ri keladi ya'ni:

onChange={handleChange} => onChange={(e, arg1) => handleChange(e)}

Bundan tashqari kodimiz unchalik ham clean emas. Balki bu usulni bitta joyda ishlatsak uncha bilinmas lekin bu kodimiz bir nechta joyida qayta-qayta ishlatilsa ayniqsa refactor qilishda muammo yaqqol ko'rinadi.

Sodda yechim: curried funksiya bilan kodimizni quyidagi elegant & clean ko'rinishga olib kelishimiz mumkin:

const handleChange = (type: string) => (e: Event) => {
  // input event va type bilan bog'liq kodimiz
}

return (
  <>
    <!-- ... -->
    <input onChange={handleChange('point')} />
    <!-- ... -->
    <input onChange={handleChange('line')} />
    <!-- ... -->
    <input onChange={handleChange('polygon')} />
    <!-- ... -->
  </>
)
Enter fullscreen mode Exit fullscreen mode

Ya'ni funksiya qaytaradigan funksiyani event handler sifatida ishlatamiz.

Curried funksiyalar haqida ushbu linkdan batafsil ma'lumot olishingiz mumkin: https://javascript.info/currying-partials

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay