CuiPengFei CuiPengFei -4 years ago 105
React JSX Question

How does react js ensure immutability of props?

function Welcome(props) {
return <h1>Hello, {}</h1>;

const element = <Welcome name="Sara"/>;

I have this in jsx.

It compiles to this js:

function Welcome(props) {
return __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement(
__source: {
fileName: _jsxFileName,
lineNumber: 7
__self: this
"Hello, ",

var element = __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement(Welcome, { name: "Sara", __source: {
fileName: _jsxFileName,
lineNumber: 10
__self: this

It looks like normal js to me.

enter image description here

So I put a break point here in chrome.

When it ran to that break point, I went to chrome's console and did this:
enter image description here

These 3 expressions were typed into the console and executed when the break point was on.

It seems like I really can not change properties of the variable named props.

But the props object looks like an innocent object, how is this implemented in react js?

Answer Source

The source code

// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
  configurable: false,
  enumerable: false,
  writable: false,
  value: source,
if (Object.freeze) {

The props are created using Object.defineProperty which gives you and ability to set writable: false and then "freezing" it with Object.freeze:

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. The method returns the object in a frozen state.

JSFiddle brief example (open the console before running):

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download