Wednesday, September 29, 2021

React: Props are read-only

Props are read-only

Props passed in to component are read-only, they can never be changed within the received component. If a component tries to update the prop value passed to it , an exception will be thrown for the error "cannot assign to read-only property". Note, if the prop value is an object, then within the received component, it can change the object's property value without causing any exception, however, React will not detect the change of the prop's value, and will not render the component again for this change.

In the parent component which sets the props, if the prop is set from a regular js let variable, then after the child component is rendered, updating the let variable's value, i.e the props value passed to the child component, React will not detect the prop change and will not re-render the child component based on the updated prop value. The prop value passed to child component is just a snapshot when rendering the child component, and the parent component will not track any future change of a regular js variable. 

In short, React does not care about regular js variable change, and will not render again based on those changes.

In order to let React knows the change, useState hook should be used.



No comments:

Post a Comment