Feature | State | Props |
---|---|---|
Ownership | Owned and managed internally by component | Defined and passed by parent component |
Mutability | Mutable; can be updated using setState()
|
Immutable; cannot be changed within component |
Scope | Local to component | Passed from parent to child components |
Initialization | Typically initialized within constructor for class components or using useState() hook for functional components |
Passed as attributes from parent component |
Component-Specific | Each component instance maintains its own state | Passed down from parent to child components |
Control | Controlled and managed by the component | Controlled by parent component |
Communication | Primarily for managing component-specific data | Used for communication between parent and child components |
Updates | Can trigger re-renders within the component | Changes in props trigger re-renders in the child component |
Usage | Managing internal component state | Configuring child components and facilitating communication between them |
Let's illustrate each point with examples:
-
Ownership:
- State:
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } // ... }
-
Props:
// ParentComponent.js import ChildComponent from './ChildComponent'; function ParentComponent() { return <ChildComponent name="John" />; }
-
Mutability:
- State:
this.setState({ count: this.state.count + 1 });
- Props: Props are immutable and cannot be changed within the component.
-
Scope:
- State: State is local to the component and not accessible outside of it.
- Props: Props are passed down from parent to child components and can be accessed within the child component.
-
Initialization:
- State:
const [count, setCount] = useState(0);
-
Props:
// ParentComponent.js <ChildComponent name="John" />
-
Component-Specific:
- State: Each instance of a component maintains its own state.
- Props: Props are passed from parent components and can be different for each instance of the child component.
-
Control:
- State: Controlled and managed by the component itself.
- Props: Controlled by the parent component, and changes are propagated down to child components.
-
Communication:
- State: Used for managing component-specific data that can change over time.
- Props: Used for passing data and behavior from parent to child components.
-
Updates:
- State: Changes to state trigger re-renders within the component.
- Props: Changes in props trigger re-renders in the child component.
-
Usage:
- State: Used for managing internal component state, such as form inputs, toggle states, etc.
- Props: Used for configuring child components and facilitating communication between them.
Top comments (0)