Skip to content

Instantly share code, notes, and snippets.

@richseviora
Created October 5, 2017 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richseviora/57f969daa8ff576c8f52d1d279e6909e to your computer and use it in GitHub Desktop.
Save richseviora/57f969daa8ff576c8f52d1d279e6909e to your computer and use it in GitHub Desktop.
Handler Allocation Examples
class ParentComponent extends React.Component<any, any>{
render(): JSX.Element {
return (
<div>
<EveryRenderComponent id={1} doTheThing={this.doTheNumberThing} />
<OnMountComponent id={2} doTheThing={this.doTheNumberThing} />
<OnParentComponent id={3} doTheThing={this.doTheDataSetThing} />
</div>
)
}
doTheNumberThing = (id: number) => {
console.log("Zhu Li! Do the thing", id);
}
doTheDataSetThing = (event: any) => {
console.log("Zhu Li! Do the thing", event.target.dataSet.id);
}
}
// Allocates handler on every render. IS BAD.
class EveryRenderComponent extends React.Component<any, any> {
render(): JSX.Element {
return (
<button onClick={() => this.props.doTheThing(this.props.id)}/>
);
}
}
// Allocates handler on initializing only.
class OnMountComponent extends React.Component<any, any> {
render(): JSX.Element {
return (
<button onClick={this.doTheThing}/>
);
}
private doTheThing = (event: any) => {
this.props.doTheThing(this.props.id);
}
}
// Handler is allocated once per parent. Seems ideal for huge lists of items.
class OnParentComponent extends React.Component<any, any> {
render(): JSX.Element {
return (
<button onClick={this.props.doTheThing} data-id={this.props.id}/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment