BuildContex + widget tree - mobile

I am following flutter's documentation about the BuildContext class because it is not clear for me how and why to use this class.
Widget build(BuildContext context) {
// here, Scaffold.of(context) returns null
return Scaffold(
appBar: AppBar(title: Text('Demo')),
body: Builder(
builder: (BuildContext context) {
return FlatButton(
child: Text('BUTTON'),
onPressed: () {
// here, Scaffold.of(context) returns the locally created Scaffold
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('Hello.')
));
}
);
}
)
);
}
I do not get this paragraph:
The BuildContext for a particular widget can change location over time
as the widget is moved around the tree. Because of this, values
returned from the methods on this class should not be cached beyond
the execution of a single synchronous function.
BuildContext objects are actually Element objects. The BuildContext
interface is used to discourage direct manipulation of Element
objects.
as the widget is moved around the tree -> how does this happen?
As per my understanding (and please correct me if I am wrong here) the widget tree is basically how the widgets are "stacked" and how they build each other. Since it is not recommended to have sub-widgets referenced as properties in your CustomWidget class how do I change the position in a tree of a widget returned during the build method (or how does this happen by default because of the framework)

This tree change typically happens when the build method conditionally build its descendants
Example:
Widget build(BuildContext context) {
return condition
? Foo()
: Bar(child: Foo());
}
With such build method, the BuildContext of the Foo widget changes when condition changes.

Related

Using class member as a type

I want to tell Typescript that one member of one of my class is coming from another class.
For example:
Class Main{
getDataFromChild(data){
console.log(data)
}
}
Class Child{
getDataFromChild: Main.getDataFromChild //<== something like this
}
Use Case
My use case is React parent passing method down to React child. I want my IDE to navigate to Parent method decleration when I click on the passed method inside child.
export default class Parent extends Component {
simplifiedFunction (value) { // Line A
console.log(value)
}
render () {
return (
<div>
<Child
simplifiedFunction = {this.simplifiedFunction}
/>
</div>
)
}
}
export default class Child extends Component {
render () {
return (
<div>
<h1 onClick= { () =>
this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)//<== ctrl + click on simplifiedFunction should take me to its definition in parent class (Line A)
}
> Something</h1>
</div>
)
}
}
You could define an interface (named or anonymous):
interface SharedFeature {
sharedFunction: () => void;
}
and then implement it on the parent
class Parent extends React.Component implements SharedFeature {
sharedFunction() { ... }
render() { return <Child sharedFunction={sharedFunction} />; }
}
finally you can use the interface as part of the Child component's props
class Child extends React.Component<SharedFeature, {}> {
render() {
return <div>
{this.props.sharedFunction()}
</div>;
}
}
When using Component class you can take advantage of it's two generic arguments, first one defined the interface of props and the second one defines interface of the state. You can either use SharedFeature interface directly or extend another interface by it and then use that interface for props.
I dont know what kind of IDE you use but usually in this case when you do "Go to implementation" the IDE should succesfuly locate class Parent as it implements the interface that defines the function sharedFunction();
Beware that if you do "Go to definition" you WILL be taken to the declaration of the interface SharedFeature. If you want to use "Go to definition" nontheless (antipattern)use the class Parent itself as type for class Child's props. However this also makes Parent's method render() and ANY OTHER MEMBERS part of the props aswell.
I don't think this will work the way you are hoping it will. Namely your <Child/> component shouldn't have any awareness as to what passed it the simplifiedFunction prop. In your case, you happen to be passing it in from <Parent/>, but you should be able to pass in any function that satisfies the contract of the function. Imagine you had 3 other components that passed in different functions, your child component should never have to care about that.
Your question says that you "want to tell Typescript that one member of one of my class is coming from another class." This is an XY problem, in the sense that you say you want to do one thing (copy a method from one class to another) but your goal is something else (passing a method to a React component), and this should be done a different way.
Luk's answer gives a good solution for your actual use case. In my answer I'll address the original question about copying a method from one class to another, and explain why doing that is not a good solution.
Strictly speaking, the answer is simple:
class Main {
foo(): void {
console.log('bar');
}
}
class Child {
foo = Main.prototype.foo;
}
However, do not do this. You will be arrested by the OOP police, and sent to OOP jail.
It almost always doesn't make sense to do this. A method on the class Main may make use of properties that are defined in that class. Child is not a subclass of Main so it does not necessarily have the same properties. What if it's like this?
class Main {
x: string = 'bar';
foo(): void {
console.log(this.x);
}
}
class Child {
foo = Main.prototype.foo;
}
Now what is new Child().foo() supposed to do? A Child has no x property to log.
If the foo method really doesn't access any of Main's properties, and this fact is part of Main's contract (as depended on in the Child class), then the method should be static and the Child class should invoke it as Main.foo().
If the foo method does access some of Main's properties, but only properties shared by the Child class, then you should design your class hierarchy so that either Child is a subclass of Main, or so that those properties and the foo method belong to a common superclass, so that they can be shared by inheritance.

ReactJS variables problems. It's updating variables that are not being touched

I'm working on a ReactJS app and i'm a new comer.
I have a Component like this
class Type extends React.Component {
constructor(props) {
super(props);
this.state = {
name : props.type.name,
description : props.type.description,
price : props.type.price,
imageList : props.type.images,
mode : 'view',
// i'm cloning the whole object
clone : props.type
};
}
handleDeleteImage(event) {
const imageId = event.target.getAttribute('data-imageId');
// get the current imageList of this Component
var imageList = this.state.imageList;
// checking the length of 2 image list before removing the
// targeted image
console.log(imageList.length) // displays 3
console.log(this.state.clone.images.length) // displays 3
// remove the targeted imageId
imageList.splice(imageId, 1);
// checking the length of 2 image list after removing the
// targeted image
console.log(imageList.length) // displays 2
console.log(this.state.clone.images.length) // displays 2
}
}
So what i'm doing here is i want to clone the object so when the user changes there mind and doesn't want to make changes anymore, they can hit the cancel button and everything is back to the state they were before (i have a function to handle this as well. I set the fields -name, description, price- to the values of the clone)
But as you can see, i didn't touched the image list in the clone at all still it got changed anyway.
Am i doing anything wrong here?
Thank you for any help.
Hey guys! So I realized that the concept I used in this service is not so efficient.
Like #Michael McQuade said, I should control the data in one flow only which is changing the data in the parent Component, not the child ones. I also reviewed the ReactJS Documentation and I can see why.
But with that being said. Let's say I'm working on a Component which has lots of Child-Component, does that mean I have to callback all the way up to the Parent Component to make changes in the Child one? And does that mean i must have multiple handlers in the Parent one that will be passed down to the Child that needs them?
I hope my question doesn't border you guys. Thanks!
You're using state and props together in a way I wouldn't recommend.
Instead of trying to make a copy of the props and storing it as state, make a stateless function and pass down a function which handles the deletion.
Here is an example:
class Child extends React.PureComponent {
render () {
return (<button onClick={this.props.handleBye}>{this.props.text}</button>)
}
}
class Parent extends React.PureComponent {
state = {
text: "Hello"
}
handler = () => {
this.setState({text: "bye"})
}
render() {
return (<Child text={this.state.text} handleBye={this.handler} />)
}ˆ
}
ReactDOM.render(<Parent />, document.body)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
This line will not clone an object, rather it will create a reference
clone : props.type
To clone you can use various techniques (depending on your need) one simple one would be
clone: Object.assign({}, props.type)
beware that this will only create a shallow copy of the object.
To create a deep copy you can use
clone: JSON.parse(JSON.stringify(props.type))
this is an easy technique but it is slow and will not copy dates correctly.
If you need fast and reliable deep clone you better search for something else that suits your needs (maybe a library like lodash).
this.state.clone is just a reference to the props.type object. So when you use splice() you change the contents of the array and therefore "mutate" props.type.
If you really want to clone the object do it like that:
this.state = {
clone: {...props.type} // create a new object and spread the props.type object properties
}
You can read more about the spread operator here

Reactjs → static methods without access to "this", what's the alternative?

EDITED: Static methods don't have access to "this". The underlying question is then, how in reactjs should you organize the code, if you'd like to separate functionalities in different classes? the only way to call the methods of these classes is then by making them "static". Is it really the only way? What are you supposed to do? Create one big class so that all methods will have access to "this"?
EDITED2: What I have done is then to avoid writing a static method that needs to have access to the state. In particular, I've used a promise to return the value to the class that does have access to the state.
static Parse(cvs_string) {
return new Promise((resolve, reject) => {
Papa.parse(cvs_string, {
header: true,
skipEmptyLines: true,
complete: (results) => resolve(results)
});
});
}
EDITED3: But, as said in the comments, it's nonesense to build a class that also extends from Component if the main reason is to provide helper functions, so at the end:
import Papa from 'papaparse';
export const ParseCsv = (csv_string) => {
return new Promise((resolve, reject) => {
Papa.parse(csv_string, {
header: true,
skipEmptyLines: true,
complete: (results) => resolve(results)
});
});
}
---- [previous]
Why is this not working? Shouldn't I have access to setstate here?
import React, { Component } from 'react';
import Papa from 'papaparse';
class PapaParse extends Component {
constructor(props) {
super(props);
this.Parse = this.Parse.bind(this);
this.updateData = this.updateData.bind(this);
}
static Parse(cvs_string) {
Papa.parse(cvs_string, {
header: true,
skipEmptyLines: true,
// complete: (results) => { // this gives the same error
complete: function(results) {
PapaParse.updateData(results);
}
});
}
static updateData(results) {
console.log(results); // results are the expected ones
PapaParse.setState({data: results.data}); // here the error, or
this.setState({data: results.data}); // here the same error
}
}
export default PapaParse;
I can solve this by sending "this" as a variable, in
PapaParse.Parse(response, this);
and then in the PapaParse component
static Parse(cvs_string, that) {
...
PapaParse.updateData(results, that);
...
static updateData(results, that) {
...
that.setState({data: results.data});
So I understand that the "this" is lost when I'm calling a method of a componenet without invoking it with the "tag", and merely calling it as a static method.
Then, what I'm doing here is what I'm supposed to do? Or what would be the best way to do this?
Static methods are intended for code that doesn't depend on class instance, because there's none. There are not so many good use cases for static methods, because if a function isn't directly linked to a class as an entity, it possibly doesn't need to be a part of it. One of use cases is React component getDerivedStateFromProps hook which is pure function that needs to defined as a method (because it's a hook that should be accessed as class property by the framework), it forces a developer to not use class instance and focus on function input and output.
Since the method needs class instance and setState instance method in particular, static methods are not applicable here. None of these methods should be static:
class PapaParse extends Component {
Parse(cvs_string) {
Papa.parse(cvs_string, {
header: true,
skipEmptyLines: true,
complete: (results) => {
this.updateData(results);
}
});
}
updateData(results) {
console.log(results);
this.setState({data: results.data});
}
}
This is same problem as explained in this answer:
this.Parse = this.Parse.bind(this);
It's a mistake to bind static method to class instance, especially in a class that isn't a singleton by design and is expected to be instantiated multiple times (React component class is). There can be multiple class instances, this may result in bugs and memory leaks.
If Parse method is supposed to be triggered outside this class, this should be done in a way that is idiomatic to React, e.g. get PapaParse component ref in parent component and access instance method on it:
// in constructor
this.papaParseRef = React.createRef();
...
// in render
<PapaParse ref={this.papaParseRef}/>
The method will be available as this.papaParseRef.current.Parse() after render.
PapaParse.setState({data: results.data}); // here the error
Should be this.setState so you reference the instance, not the class.
Declare updatedata() as an arrow function.
updatedata=(results) => {
//this.setState will work here
}

Backbone => React - Higher Order Components, inheritance and specialisation

I have a legacy Backbone app which I have begun to rewrite in React. The app has a main view containing two subviews, arranged vetically. The top panel displays some data, and the bottom one displays the result of some algorithm taking this data as input. Since I have many different data sources, each with a different algorithm applied to it, I have an abstract base View class, which I then subclass for each data source, adding, decorating and overriding methods as necessary. Somewhat like this:
// Base View.
const BaseView = Backbone.View.extend({
events: {},
initialize() {
this.subViewA = // instantiate subview...
this.subViewB = // instantiate subview...
},
generateResultData() {
// 'Abstract' method which should be specialised to generate data rendered by subViewB...
},
render() {
// render subviews...
},
});
// Derived View.
const Derived = BaseView.extend({
events: {
// event handlers...
},
add(a, b) {
return a+b;
},
// additional methods...
generateResultData() {
return {
result: this.add(2,2);
}
},
})
This results in a shallow hierarchy of many similar View classes. It's all terribly imperative, but it's a simple, intuitive and easy-to-reason-about pattern, and just works. I'm struggling to see how to achieve the same thing in React, however. Given that subclassing of subclasses of React.Component is considered an anti-pattern, my focus has naturally been on composition, and in particular Higher Order Components. HOCs (which I find beautiful, but unintuitive and often just downright confusing) seem to involve adding general features, rather than specialising/refining something more general. I have also considered passing in more specialised versions of Componenet methods through props. but that just means I have to use the same boilerplate Component definition over and over again:
// General functional component, renders the result of prop function 'foo'.
function GeneralComponent(props) {
const foo = this.props.foo || ()=>"foo";
return (
<div>
<span> { this.props.foo() } </span>
</div>
)
}
// Specialised component 1, overrides 'foo'.
class MySpecialisedComponent extends React.Component {
foo() {
return this.bar()
}
bar() {
return "bar"
}
render() {
return (
<GeneralComponent foo={this.foo} />
)
}
}
// Specialised component 2, overrides 'foo' and adds another method.
class MyOtherSpecialisedComponent extends React.Component {
foo() {
return this.bar() + this.bar()
}
bar() {
return "bar"
}
baz() {
return "baz"
}
render() {
return (
<GeneralComponent foo={this.foo} />
)
}
}
The above is a very simplistic case, obviously, but essentially captures what I need to do (though I would of course be manipulating state, which the example does not do, for simplicity). I mean, I could just do things like that. But I want to avoid having to repeat that boilerplate all over the place. So is there a simpler and more elegant way of doing this?
Generally, if a component is stateless and doesn't use lifecycle hooks, there are no reasons for it to be Component class. A class that acts as a namespace and doesn't hold state can be considered an antipattern in JavaScript.
In constrast to some other frameworks, React doesn't have templates that would need to map variables in order for them to be available in view, so the only place where bar function needs to be mentioned is the place where it's called. JSX is an extension over JavaScript, JSX expressions can use any names that are available in current scope. This allows to compose functions without any classes:
const getBar => "bar";
const getBaz => "baz";
const getBarBaz => getBar() + getBaz();
const MySpecialisedComponent = props => <GeneralComponent foo={getBar} />;
const MyOtherSpecialisedComponent = props => <GeneralComponent foo={getBarBaz} />;
An anonymous function could be passed as foo prop instead of creating getBarBaz but this is generally discouraged because of unnecessary overhead.
Also, default prop values could be assigned with defaultProps without creating new ()=>"foo" function on each component call:
function GeneralComponent({ foo }) {
return (
<div>
<span> {foo()} </span>
</div>
)
}
GeneralComponent.defaultProps = { foo: () => 'foo' };
IMO what is throwing you off isn't inheritance vs composition, it's your data flow:
For example, many of my derived views need to do custom rendering after the main render. I'm using a third-party SVG library, and the data rendered into the 'result' subview is derived from analysis of rendered SVG elements in the main data view above it
So what you're trying to do here is have a child update props of a distantly related component after render, correct? Like this?
// after the svg renders, parse it to get data
<div id="svg-container">
<svg data="foo" />
<svg data="bar />
</div>
// show parsed data from svg after you put it through your algos
<div id="result-container">
// data...
</div>
There's a lot of state management libraries out there that will help you with this problem, that is, generating data in one component and broadcasting it to a distantly related component. If you want to use a tool built-in to react to address this you may want to use context, which gives you a global store that you can provide to any component that wants to consume it.
In your example your child classes have data-specific methods (add, etc.). IMO it's more typical in react to have a generic class for displaying data and simply passing it down map functions as props in order to rearrange/transform the rendered data.
class AbstractDataMap extends PureComponent {
static defaultProps = {
data: [],
map: (obj, i) => (<div key={i}>{obj}</div>)
};
render() {
const { data, map, children } = this.props;
const mapped = data.map(map);
return (
<Fragment>
{mapped.map((obj, i) => (
children(obj, i)
))}
</Fragment>
);
}
}
// in some other container
class View extends Component {
render() {
return (
<div>
<AbstractDataMap data={[1, 2, 3]} map={(n) => ({ a: n, b: n + 1 })}>
{({ a, b }, i) => (<div key={i}>a: {a}, b: {b}</div>)}
</AbstractDataMap>
<AbstractDataMap data={[2, 4, 6]} map={(n) => (Math.pow(n, 2))}>
{(squared, i) => (<div key={i}>squared: {squared}</div>)}
</AbstractDataMap>
</div>
);
}
}
IMO this pattern of using an HOC to abstract away the labor of explicitly using .map in your render calls (among other uses) is the pattern you are looking for. However, as I stated above, the HOC pattern has nothing to do your main issue of shared data store across sibling components.
Answering my own question, which I've never donw before...
So my question really arose from a concern that I would need to refactor a large, imperative and stateful codebase so as to integrate with React’s composition-based model (also with Redux). But it occurred to me after reading the (very insightful and helpful) responses to my question that my app has two parallel parts: the UI, and an engine which runs the algorithms (actually it's a music analysis engine). And I can strip out the Backbone View layer to which the engine is connected quite easily. So, using React’s context API I've built an ‘AnalysisEngineProvider', which makes the engine available to subcomponents. The engine is all very imperative and classically object-oriented, and still uses Backbone models, but that makes no difference to the UI as the latter has no knowledge of its internals - which is how it should be (the models will likely be refactored out at some point too)...
The engine also has responsibility for rendering the SVG (not with BB views). But React doesn’t know anything about that. It just sees an empty div. I take a ref from the div and pass it to the engine so the latter knows where to render. Beyond that the engine and the UI have little contact - the divs are never updated from React state changes at all (other components of the UI are though, obviously). The models in the engine only ever trigger updates to the SVG, which React knows nothing about.
I am satisfied with this approach, at least for now - even if it's only part of an incremental refactor towards a fully React solution. It feels like the right design for the app whatever framework I happened to be using.

Reconciliation in React detailed explanation

I am new to react JS. Can anyone explain reconciliation exactly how it works. I have tried understanding it from react official site but didn't got it.
This is how I understand :
You would agree that react makes thing simple and faster using components .
With JSX we can make things easier for user-defined components .
End of the day all of it gets translated to pure JavaScript (I assume you understand how React.createElement works)with function calls holding other function calls as its arguments/properties holding yet other function calls and so on ..
Anyway nothing for us to worry about as react does this on its own internally .
But how does this gives us an UI ?
Why it is faster from other UI libraries ?
<-- ALL HAIL ReactDOM library and the render method -->
An ordinary ReactDOM call looks like this :
// I have avoided the usage of JSX as its get transpiled anyway
ReactDOM.render(
React.createElement(App, { //if any props to pass or child }), // "creating" a component
document.getElementById('#root') // inserting it on a page
);
Heard about VirtualDOM ? { yes : 'Good'} : { no : 'still Good'} ;
The React.createElement construct element object with type and props based on the components we have written and place the child elements under a children key inside props.
It recursively does this and populates a final object which is ready to be converted to HTML equivalent and painted to the Browser.
This is what VirtualDOM is, which resides in reacts memory and react performs all its operation on this rather on actual Browser DOM .
It looks something like this:
{
type: 'div',// could be other html'span' or user-diff 'MyComponent'
props: {
className: 'cn',
//other props ...
children: [
'Content 1!', // could be a component itself
'Content 2!', // could be a component itself
'Content n!', // could be a component itself
]
}
}
After a Virtual DOM object is built, ReactDOM.render will transform it into a DOM node our browser can paint the UI according to those rules:
If a type attribute holds a string with a tag name—create a tag with all attributes listed under props.
If we have a function or a class under type—call it and repeat the process recursively on a result.
If there are any children under props—repeat the process for each child one by one and place results inside the parent’s DOM node.
The Browser paints it to the UI , this is an expensive task .
React is very smart to understand this.
Updating the component means creation of a new object and paint to UI. Even if a small change is involved it will make the whole DOM tree recreated .
So how do we make the Browser never have to create DOM each time rather paint only the necessary things.
This is where we need Reconciliation and the diffing algorithm of React ..
Thanks to react we don't have to do it our self manually , its taken care of internally here is a nice article to understand deeper
Now you can even refer the official React docs for Reconsiliation
Few points worth noting :
React implements a heuristic O(n) algorithm based on two assumptions:
1) Two elements of different types will produce different trees.
2) The developer can hint at which child elements may be stable across different renders with a key prop.
In practice, these assumptions are valid for almost all practical use cases.
If these are not met it will cause performance issues.
I am just copy Pasting few other points just to give a idea how its done :
Diffing :
When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.
Scenario 1: type is a string, type stayed the same across calls, props did not change either.
// before update
{ type: 'div', props: { className: 'cn' , title : 'stuff'} }
// after update
{ type: 'div', props: { className: 'cn' , title : 'stuff'} }
That is the simplest case: DOM stays the same.
Scenario 2: type is still the same string, props are different.
// before update:
{ type: 'div', props: { className: 'cn' } }
// after update:
{ type: 'div', props: { className: 'cnn' } }
As type still represents an HTML element,React looks at the attributes of both, React knows how to change its properties through standard DOM API calls, without removing the underlying DOM node from a DOM tree.
React also knows to update only the properties that changed. For example:
<div style={{color: 'red', fontWeight: 'bold'}} />
<div style={{color: 'green', fontWeight: 'bold'}} />
When converting between these two elements, React knows to only modify the color style, not the fontWeight.
///////When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, and calls componentWillReceiveProps() and componentWillUpdate() on the underlying instance.
Next, the render() method is called and the diff algorithm recurses on the previous result and the new result.
After handling the DOM node, React then recurses on the children.
Scenario 3: type has changed to a different String, or from String to a component.
// before update:
{ type: 'div', props: { className: 'cn' } }
// after update:
{ type: 'span', props: { className: 'cn' } }
As React now sees that the type is different, it would not even try to update our node: old element will be removed (unmounted) together with all its children.
It is important to remember that React uses === (triple equals) to compare type values, so they have to be the same instances of the same class or the same function.
Scenario 4: type is a component.
// before update:
{ type: Table, props: { rows: rows } }
// after update:
{ type: Table, props: { rows: rows } }
“But nothing had changed!”, you might say, and you will be wrong.
If type is a reference to a function or a class (that is, your regular React component), and we started tree reconciliation process, then React will always try to look inside the component to make sure that the values returned on render did not change (sort of a precaution against side-effects). Rinse and repeat for each component down the tree—yes, with complicated renders that might become expensive too!
To make sure such things come clean:
class App extends React.Component {
state = {
change: true
}
handleChange = (event) => {
this.setState({change: !this.state.change})
}
render() {
const { change } = this.state
return(
<div>
<div>
<button onClick={this.handleChange}>Change</button>
</div>
{
change ?
<div>
This is div cause it's true
<h2>This is a h2 element in the div</h2>
</div> :
<p>
This is a p element cause it's false
<br />
<span>This is another paragraph in the false paragraph</span>
</p>
}
</div>
)
}
}
Children =============================>
we also need to account for React’s behavior when an element has more than one child. Let’s say we have such an element:
// ...
props: {
children: [
{ type: 'div' },
{ type: 'span' },
{ type: 'br' }
]
},
// ...
And we want to shuffle those children around:
// ...
props: {
children: [
{ type: 'span' },
{ type: 'div' },
{ type: 'br' }
]
},
// ...
What happens then?
If, while “diffing”, React sees any array inside props.children, it starts comparing elements in it with the ones in the array it saw before by looking at them in order: index 0 will be compared to index 0, index 1 to index 1, etc.
For each pair, React will apply the set of rules described above.
React has a built-in way to solve this problem. If an element has a key property, elements will be compared by a value of a key, not by index. As long as keys are unique, React will move elements around without removing them from DOM tree and then putting them back (a process known in React as mounting/unmounting).
So Keys should be stable, predictable, and unique. Unstable keys (like those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
Because React relies on heuristics, if the assumptions behind them are not met, performance will suffer.
When state changes: =========================================>
Calling this.setState causes a re-render too, but not of the whole page, but only of a component itself and its children. Parents and siblings are spared. That is convenient when we have a large tree, and we want to redraw only a part of it.
Reconciliation in the context of React means to make React's virtual DOM tree consistent with the real DOM tree of your browser. This happens during (re-)rendering
The key point is that there is no guarantee that a specific element of React's virtual DOM refers to the same DOM node of your browser for its complete lifecycle. The reason for this is React's approach to update the DOM efficiently. You can use the special key property to solve this issue, if a component contains dynamic or stateful children.

Resources