I\'ve read a bunch of articles about the use of () => {}
syntax, binding in the constructor, binding in the props etc.. but from what I understand, binding
Syntactically, I much prefer arrow functions to binding (especially since only arrow functions facilitate passing extra arguments to event handlers). Understanding the performance penalty associated with arrow functions, I created a utility function that accepts arrow function definitions which will be cached for the lifetime of a component:
utils.js
export function createLambdaCache() {
const result = {};
return (key, lambda) => {
if (!(key in result)) {
result[key] = lambda;
}
return result[key];
};
}
component.js
class MyComponent extends React.Component {
render() {
return (
...
// below 'btnEvent' string is used as a key to cache the event reference for subsequent renders
typescript version of above createLambdaCache
:
type evtHandler = (evt: E) => void;
export function createLambdaCache() {
const result: {[key in keyof T]: evtHandler} = {} as any;
return (key: keyof T, lambda: evtHandler) => {
if (!(key in result)) {
result[key] = lambda;
}
return >result[key];
};
}