React components accept arbitrary inputs
(called “props”) and return React elements describing what should appear on the screen.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
So props able parent
components to deliver data to child
components.
function Parent() {
return (
<Child data="this is props for child!"/>
)
}
function Child(props) {
return <h1>{props.data}</h1>
}
Props have 2 major characteristics.
props must be read-only they should not be modified when passed to other components.
// 1st example
function Child(props) { // props is 1
const modified = props.number + 1 ❌
return <h1>{modified}</h1>
}
It is more easy to understand why props must be immutable according to the fact that props are more likely a reference from parent component. Therefore it is the parent components who owns the data.
// 2nd example
function Child(props) {
props.data = "I want to change this" ❌
return <h1>{props.data}</h1>
}
Props must be one-way
data flow, which means props need to be passed only from parent components to child components.
Props-drilling
occurs when a parent component passes data down to its children and then those children pass the same data down to their own children.
If the depth gets too deep, props-drilling could make React app difficult to manage and maintain.
Immutability and unidirection have benefits.
- comprehend the logic more quickly
- simplify the data flow
Props is one of the most important concept in React. Those two characteristics keep the React app consistent and reliable in controlling the flow of data between components.