memoize-bind
Memoized function binding
memoize-bind
performs the same job as Function.prototype.bind()
, however it memoizes the result for future reference.
This ensures that calling memoize-bind
repeatedly with the same arguments will always return the same bound function, which can be particularly useful within React.js render methods (see below).
Installation
npm install memoize-bind
Usage
bind(fn, [context], [...args])
Create a new function that, when called, will invoke fn
with the this
keyword set to context
.
If any args
are specified, they will be prepended to the list of arguments supplied when calling the newly-created function.
Example
;; const context = name: 'foo' ;const fn = { return thisname ...args; };const args = 'bar' 'baz' const boundFn = ; // Identical to fn.bind(context, ...args)const boundFn2 = ; // Returns the same function; ; // Returns ['foo', 'bar', 'baz', 'qux']
memoize-bind
?
Why Function.prototype.bind()
is often used within React components, where callbacks need to be bound to the current component instance (optionally with arguments pre-applied).
While convenient, using .bind()
within a render function can be problematic for React's dirty-checking algorithm, seeing as a new function instance would be returned on each render, leaving the React reconciler unable to tell that two functions generated during subsequent renders are indeed identical.
memoize-bind
fixes this problem by always returning the same bound function when called with the same arguments, allowing bound functions to be used within straightforward equality checks in the component's shouldComponentUpdate
method (as used by PureComponent
/ PureRenderMixin
).
This means that you can keep all the convenience of the .bind()
method, without having to worry about affecting performance.
React Example
;; { const items = thisprops; return <ul> items </ul> ; } { if !itemisCompleted thisprops; } static propTypes = items: PropTypes onComplete: PropTypesfuncisRequired ;
memoize-bind
in ES5 applications
Using memoize-bind
uses memoize-weak
internally to ensure that any memoized arguments and values can be properly garbage-collected.
memoize-weak
requires that Map
and WeakMap
are globally available. This means that these will have to be polyfilled for use in an ES5 environment.
Some examples of Map
and WeakMap
polyfills for ES5: