Properties (Props) act as conduits, that is, they allow parent components to pass data to their child components via a one-way data flow.
A state is used when a component has to store and process dynamic data, and it is always local to a component. However, since the state is local and encapsulated within a component, how can this data be shared with other components down the hierarchy? A typical React application is made up of several components, and although multiple techniques are available to share data between components, the most fundamental way is using props. Props offer a simple way for parent components to pass data to child components. In terms of usage, they are similar to the standard attributes on a component and can be bound to dynamic data using a pair of curly braces. Props are immutable, that is, the data of a prop cannot be changed. This is because the concept on which rops have been built is that of pure functions, and any changes made to the data of the parameters cannot be changed in a Prop.
Inside a class component, props can be accessed using this.props.propName. When working with function components, all props are received using a single object as an argument to the function.
Difference between state and props
|Props are passed to the components (just like in function parameters)||State is managed within the component (just like a variable is declared within a function)|
|Props are immutable||State is mutable|
|Props are used to manage data down from the view-controller||States are managed in the view-controller|
Props let you access all types of data, such as strings, numbers, objects, arrays, and functions. Since a prop is a conduit, it ultimately feeds into the component’s internal logic, which has to process and consume the incoming data.
So, you need to be careful regarding the type of data a prop receives. For instance, a prop that must receive an array of items cannot receive a string. Likewise, a prop that must expect a function cannot receive a number. Hence, it becomes important to type-check and validate the data flowing through a prop.
React offers a prop types package that exports numerous validators for all data types. These validators will show appropriate warnings in the console whenever a prop receives an incompatible type of data.
Note: These validators will only issue warnings during development. Once a production build is produced, no warning will be shown because the validation code is removed during the optimization phase.
The ‘shape’ validator type allows you to describe the shape of the object you wish to receive in a prop.