How it works

Apart from the differences in declaring the initial state using the factory or extending the component, the important concept we've learned is that each stateful React component can have an initial state.

During the lifetime of the component, the state can be modified multiple times using setState inside life cycle methods or event handlers. Every time the state changes, React renders the component again with the new state, which is why documentation often says that a React component is similar to a state machine.

When the setState method is called with a new state (or part of it), the object gets merged into the current state. For example, if we have an initial state as the following one:

  this.state = { 
text: 'Click me!'
};

And we run setState with a new parameter as follows:

  this.setState({ 
cliked: true
});

The resulting state is as follows:

  { 
cliked: true,
text: 'Click it!'
}

Every time the state changes, React runs the render function again, so there's no need for us to do anything other than setting the new state.

However, in some cases, we may want to perform some operations when the state is updated, and React provides a callback for that as follows:

  this.setState({ 
clicked: true
}, () => {
console.log('the state is now', this.state);
});

If we pass any function as a second parameter of the setState method, it gets fired when the state is updated, and the component has been rendered.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.100.48