Understanding React Lifecycle Hooks

154 views Asked by At

I'm new at React/React Native and I just began working on a company and, thus, working on existing projects. The thing is, I can't understand this Creation Lifecycle Hooks on the begining of this code:

export default class ListResult extends React.Component {
  constructor(props) {
    super(props);
    this.state.answers = props.navigation.state.params.answers;
    this.state.saving = props.navigation.state.params.saving;
    this.state.loading = false;
  }

  state = {
    answers: null,
    saving: false,
    loading: true,
    location: null,
    dialogLocation: false,
    latitude: '',
    longitude: '',
  };

  location = null;
  latitude = '';
  longitude = '';
}

Can someone please provide me some explanation why is he using the constructor to initialize the state, and after that, used state to define variables, and then, after that, he also set some values to those variables?

2

There are 2 answers

0
Dennis Vash On BEST ANSWER

Its a common mistake and even emphasised in related docs:

Avoid copying props into state! (in the constructor) This is a common mistake. Only use this pattern if you intentionally want to ignore prop updates.

This code roughly should fixed to:

class ListResult extends React.Component {
  state = {
    answers: null,
    ...
  };

  componentDidMount = () => {
    const { answers, saving } = props.navigation.state.params;
    this.setState({ answers, saving });
  };
}

As for explanation, he uses both class instances and a constructor (why?), in "modern" React, with class components you shouldn't use the constructor (instead, use class properties).

When a class is defined, the class instances evaluated first and then the constructor called, thats why he overrides the initial values in their instances.

0
gazdagergo On

Without answering the question in details I try to highlight the difference of react lifecycle thinking versus the conventional JS DOM manipulation. If you work with React you manipulate the so called "virtual dom" with your JS code and not the real DOM.

How virtual dom works in nutshell: if ANY prop or state is changing of any component in the dom tree the whole child dom tree gets re-rendered. Lifecycles means how do you handle these continuous re-renderings within the components.

But no worries. It does not mean the whole DOM gets re-rendered every time. On top of this virtual dom there is a guy called ReactDOM which continuously compares the virtual-dom states and do the necessary changes only in the real DOM.