From e4436f75a946de55630d25ea5a155a6ffb555635 Mon Sep 17 00:00:00 2001 From: Jeff Hicken Date: Tue, 13 Apr 2021 16:42:13 -0600 Subject: [PATCH] Fix for quick unmount and remounts I have a case where I am intentionally unmounting and remounting before the debounce gets run in the call stack. And I get errors from react telling me I have a memory leak. This makes that error go away. --- src/truncateString.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/truncateString.js b/src/truncateString.js index b5afa86..e36bff4 100644 --- a/src/truncateString.js +++ b/src/truncateString.js @@ -66,11 +66,13 @@ class TruncateString extends PureComponent { resetTruncate = debounce(50, () => { // this renders the original string so we can measure it - this.setState({truncating: true}, () => { - // now we render again with the truncated string - const truncatedString = this.getTruncateString(this.props.text) - this.setState({truncatedString, truncating: false}) - }) + if (this._isMounted) { + this.setState({truncating: true}, () => { + // now we render again with the truncated string + const truncatedString = this.getTruncateString(this.props.text) + this.setState({truncatedString, truncating: false}) + }) + } }) componentDidMount() { @@ -79,6 +81,7 @@ class TruncateString extends PureComponent { this.setState({truncatedString, truncating: false}) window.addEventListener('resize', this.resetTruncate) + this._isMounted = true } componentDidUpdate = (_, prevState) => { @@ -92,6 +95,7 @@ class TruncateString extends PureComponent { } componentWillUnmount() { + this._isMounted = false window.removeEventListener('resize', this.resetTruncate) }