DEV Community

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

Posted on • Edited 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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay