Skip to content

React Utils - v1.0.5

Compare
Choose a tag to compare
@ItsJonQ ItsJonQ released this 08 Jan 17:51
· 21 commits to master since this release

Add withSafeSetState HOC

This update adds a new HOC function, withSafeSetState. It enhances the
provided Wrapped component to ensure that setState only works if the
component is mounted.


withSafeSetState()(WrappedComponent)

Enhances the WrappedComponent's setState method to only work if the Component is mounted.

Arguments

Argument Type Description
WrappedComponent React.Component A React component.

Returns

React.Component: The enhanced React component.

Additional Methods

isComponentMounted()

Returns: boolean

The component is also provided with the method .isComponentMounted().

Note: This is different then React's native .isMounted() method, which they are deprecating.

Examples

import React from 'react'
import withSafeSetState from '@helpscout/react-utils/dist/withSafeSetState'

class Napoleon extends React.Component {
  ...
  componentWillUnmount() {
    setTimeout(() => {
      console.log('Tina, eat!')
      this.setState({
        feedTina: true
      })
    }, 1000)
  }
  ...
}

const EnhancedNapolean = withSafeSetState()(Napoleon)

// When EnhancedNapolean unmounts, the setState() method with feedTina will
// not be called. No warnings or errors will be thrown.

Update also resolves getDocumentFromComponent for certain React 16 versions:

#9