You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In this example, we "bind" 10 to d when we create the function divideBy10. We can say 10 is "closed" to divideBy10.
React and Closures
what React components may look like without React
Stateless Functional Component:
constMyFunctionalComponent=(props={stuff: ''})=>{returnfunction(){// renderconst{ stuff }=props;return`This is printing out props: ${stuff}`;};};constcomp=MyFunctionalComponent({stuff: 'yeah!'});console.log(comp());// This is printing out props: yeah!
Stateless Class Component:
functionMyClassComponent(props={stuff: ''}){// Constructor :this.props=props;// End Constructor// renderreturnfunction(){const{ stuff }=this.props;return`This is printing out props: ${stuff}`;};}constcomp=MyClassComponent({stuff: 'yeah!'});console.log(comp());// This is printing out props: yeah!
Stateful Class Component
functionMyStatefulClassComponent(props={stuff: ''}){// Constructor :this.props=props;this.state={count: 0};// End Constructorconstincrement=()=>{this.state.count++;};constdecrement=()=>{this.state.count--;};constrender=()=>{const{ stuff }=this.props;const{ count }=this.state;return`My Props: ${stuff}, My State: ${this.state.count} `;};// Render methodreturn{
render,
increment,
decrement
};}constcomp=/*new*/MyStatefulClassComponent({stuff: 'yeah!'});console.log(comp.render());// My Props: yeah!, My State: 0comp.increment();console.log(comp.render());// My Props: yeah!, My State: 1comp.decrement();console.log(comp.render());// My Props: yeah!, My State: 0
Partial Application (PA)
You apply some of the required parameters of a function and return a function that takes the rest of the parameters.
// Revisited from ClosuresfunctiondivideNByD(n,d){returnn/d;}constdivideBy10=curry2(divideNByD)(10);constanswer=divideBy10(20);console.log(answer);// 2
Immutable Data
Remember those higher order functions?
javascript filter - create a new list with equal or fewer items
javascript map - create a new array of apples from an array of oranges
javascript reduce - create a new elephant from a list of mice
Some Reasons why we may care about Immutable Data (not-exhaustive):
For the higher-order functions, the existing list is not modified, and the new data is created when it is needed
Mutating data opens us up for bugs, in the same vein as do stateful components, objects, services, etc. do
Functions that do not mutate their parameters are easy to test
Immutability makes our methods and applications deterministic
Side Effects
What is a Side Effect: A function or expression is said to have a side effect if it modifies some state outside its scope or has an observable interaction with its calling functions or the outside world besides returning a value.