DEV Community

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

Posted on • Updated on

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

Top comments (0)