Search code examples
javascriptreactjslifecycle

How properly unmount state within ComponentWillUnmount to avoid memory leaks?


I pass a component state as a prop to another component. It is really large. Do I have to reset the state while parent component unmounted? I just want to avoid memory leaks.

componentDidMount(){
  fetch({ /* ... */ })
    .then(res => res.json())
    .then((responseData) => {
      this.setState({
        result: responseData.meta.data
      })
    })
}
  
componentWillUnmount(){
  this.setState({
    result: undefined // IS THAT RIGHT APPROACH?
  })
}

render() {
  return (
    <DataComponent data={this.state.result}>

    </DataComponent>
  );
}

Solution

  • To prevent memory leaks, you don't have to perform this state change in componentWillUnmount method. Unmounting the component would remove the state, and so would the reference to the responseData.meta.data, which you stated is large.

    There is also another downside to this solution. This type of optimization lowers your code readability and may complicate the maintenance process in future. So try not to use this in your code as it is considered against the clean code principle.