In the React tutorial , It says
React elements are immutable. Once you create an element, you can’t change its children or attributes. An element is l
React components are built with createElement internally:
React.createElement(type, props)
And thus, when any changes applied on its props the value gets updated but not its type.
For example:
React.createElement('h1', 'Hello, world!')
// first param is type, and second is prop
Here the prop is not changed, and thus this element will not be updated.
The component could be written with createElement like:
React.createElement('div',
React.createElement('h1', 'Hello world!'),
React.createElement(....),
React.createElement(...)
)
So, whenever any of the props of the particular element gets changes, that element will only be updated.
Why only props are updated, but not type ie. element?
It's because React store them in ReactDOM object but not HTML DOM. And it carefully analyse what it needs to be updated. ReactDOM is simply an object with key:value pair.
For example, React initialize it's dom like:
var ReactDOM = {}
Now, whatever the property need update, can be handled on that.
Object.defineProperties(ReactDOM, {
type: { // creating immutable property
value: 'h1',
writable: false,
configurable: false
},
props: {
writable: true,
value: 'MY PROPS'
}
});
Object.seal(ReactDOM)
Now, the props can be changed but not type.
ReactDOM.props = 'will be updated'
ReactDOM.type = 'will not be updated'
console.log(ReactDOM.type) // 'h1'
console.log(ReactDOM.props) // 'will be updated'
I hope this makes clear up things that React's elements are immutable.
It doesn't do updates on React Element Tree ('the immutable object'). It compares previous tree with the current one and does necessary updates to the DOM.
React Element Tree is a simplified form of the DOM. It's like a snapshot. React has the current snapshot and when the state of an application changes, it creates a new state that reflects how the DOM should look like. React compares those two snapshots and makes required changes to the DOM so that it mirrors the new snapshot. After that the old, outdated snapshot is trashed and the new one becomes the current snapshot of the DOM.
Basically, you have:
DOM or external world (i.e. server) produce events that change the state. A new snapshot is created for that state based on the description. Old and new snapshots are compared and changes are introduced to the DOM. This process repeats over and over again.
You can see and learn more about React elements in this fantastic blog post: https://reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html