1

I wrote class component in my current working project and faced issues javascript heap out of memory then I found of componentWillUnmount method I used in whole project. Actually it is useful but there some components where I don't have anything to clear e.g: async calls, timeouts etc. Do I need to write componentWillUnmount there? Also I'm using varibles in main scope making them null in this method is it correct? posting an example:


var exampleOne = [];
var exampleTwo;
export class Demo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      someState: null
    };
  }
  componentWillUnmount() {
    exampleOne = null;
    exampleTwo = null;
  }

  render() {
    return <div>Hello World {this.state.someState}</div>;
  }
}

export default Demo;
Tejas
  • 894
  • 7
  • 24
Mayur Sonawane
  • 109
  • 1
  • 8

2 Answers2

1

Mainly in componentWillUnmount you need to mostly remove the Event listeners which has been added.

Eg) => Like mouse movement events for analytics and any setInterval methods.

You don't need to clear the state because when the next time it mounts it will take the initial state also the class instance also gets destroyed and re created.

I hope this will give much more understanding, You can read more this ,

Learner
  • 8,379
  • 7
  • 44
  • 82
1

there some components where I don't have anything to clear e.g: async calls, timeouts etc. Do I need to write componentWillUnmount there?

componentWillUnmount is a lifecycle event, simply writing the method and not doing anything it will not accomplish anything.

Also I'm using varibles in main scope making them null in this method is it correct

This will set the variables to null will not clear memory immediately, but it may help the garbage collection. See answers here


Regarding your architecture, it seems weird to me. I see your comment about not needing it for state, but if nothing else - shouldn't you place exampleOne and exampleTwo in your class, as such:


export class Demo extends Component {
  exampleOne = [];
  exampleTwo;

  constructor(props) {
  // ...

This will further isolate the concern of the class and help garbage collection, which should be enough for any scenario I can think of. And it should not require you to attempt to clear memory with every componentWillUnmount, which should be used for things such as unbinding events that are not cleared when a component is destructed or handle finalizing tasks when a component is unmounting.

Fredrik Schön
  • 4,888
  • 1
  • 21
  • 32