In redux, we usually comes across connect()()
syntax.
Everyone knows that, connect()()
function in redux is used for connecting the component with store.
But under the hood, what it exactly means? What can we call such functions ? Is this are normal function like foo()
thing ?
Lets see whats its exactly:
What it is knowns as ?
Currying: This methodology or syntax signature of function which takes multiple arguments one at a time
is known as 'Curried function' or in short 'Currying'
Is it same as normal / partial function foo()
?
Curry: lets you call a function, splitting it in multiple calls, providing one argument per-call.
Partial: lets you call a function, splitting it in multiple calls, providing multiple arguments per-call.
Basically both are same, Currying function helps you to manage code better than partial function and that's the reason on architecture level, usually you will come across curry functions.
Example: Lets do a sum using both partial and curry function:
Partial function:
function sum_partial(a,b,c){
return a+b+c;
}
Curried Function:
function sum_curried(a) {
return function (b) {
return function (c) {
return a + b + c
}
}
}
Calling partial function:
let res = sum_partial(1, 2, 3);
console.log(res); //6
Calling Curried function:
//Method ONE
let sc1 = sum_curried(1);
let sc2 = sc1(2);
let res2 = sc2(3);
console.log(res2); //6
Short METHOD OR Similar to connect()() in redux
let res3 = sum_curried(1)(2)(3);
console.log(res3); //6
Working JS Fiddle here
For in deep working of connect go here
For more such contents follow @msabir
Cheers!!
Top comments (3)
Nitpick: connect
Currying versus partial application (with JavaScript code)
While
connect
does return a 1-ary function that accepts a component and returns a wrapper component, the initialconnect()
call accepts up to 4 arguments - not just exactly one argument as it is the case with currying.From that perspective in looks more like partial application of an imaginary
function i.e.
rather than curried
Also
Very nicely explained in dept. Great !!, this blog was more intended to understand the underline concept behind connect() function and you made it better by explaining the working procedure in dept. Kudos to you.
Whats your thoughts in this ?