Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active January 3, 2019 21:44
Show Gist options
  • Save ccnokes/f3bf59625a1410345aa0d885ac94bc02 to your computer and use it in GitHub Desktop.
Save ccnokes/f3bf59625a1410345aa0d885ac94bc02 to your computer and use it in GitHub Desktop.
mixin class that extends your component and makes `setState` "safe". See https://codesandbox.io/s/6438ymvk8z
import * as React from 'react';
// see https://github.com/Microsoft/TypeScript/pull/13743 for what the typing in here's all about
type Constructor<T> = new (...args: any[]) => T;
const isMounted_Symbol = Symbol('isMounted');
/**
* This is for when you're calling setState in uncancellable async callbacks.
* NOTE: Doing this can mask memory leaks so be careful
* TODO: typing might need some work
*/
export function makeSafeSetStateComponent<T extends Constructor<React.Component>>(ComponentType: T) {
return class SafeSetStateComponent extends ComponentType {
// use symbol so we don't inadvertently override a property on the parent class
private [isMounted_Symbol] = false;
setState(...args) {
if (this[isMounted_Symbol]) {
super.setState.apply(this, args);
}
}
componentDidMount() {
this[isMounted_Symbol] = true;
super.componentDidMount && super.componentDidMount();
}
componentWillUnmount() {
this[isMounted_Symbol] = false;
super.componentWillUnmount && super.componentWillUnmount();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment