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.