Props in React are used to pass data from a parent component to its child components. They help customize the behavior and appearance of components while maintaining a unidirectional data flow.
In React, props are immutable by default. This means that once props are passed to a child component, they cannot be modified directly within that child component.
Immutability of props brings multiple advantages to your application:
import React, { useState } from 'react';
const ParentComponent = () => {
const [count, setCount] = useState({ count: 0 });
return (
<div>
<ChildComponent {...count} />
<button onClick={() => setCount({ count: 10 })}>Update Count</button>
</div>
);
};
const ChildComponent = ({ count }) => {
// Attempting to modify the props directly will result in an error
// const updatedCount = { count: count + 1 };
return <p>Count: {count.count}</p>;
};
In this example:
ParentComponent
maintains the count in its state.ChildComponent
as props.count
prop within the child will cause an error since props are read-only.React enforces immutability of props to promote a predictable and stable architecture. If you need to update the data passed to a component, the appropriate way is to modify the parent’s state and re-render the child with new props.