What are Props?
Props (short for properties) are read-only data passed from parent to child components. They allow components to be dynamic and reusable. Props are immutable – components cannot modify their own props.
Basic Props Usage
Prop Types (Type Checking)
TypeScript with Props
Children Prop
Render Props Pattern
Props Drilling and Solutions
Spreading Props
Common Props Patterns
| Pattern | Description | Example |
|---|---|---|
| Default Props | Fallback values | variant = 'primary' |
| Required Props | Must be provided | name: string.isRequired |
| Optional Props | May be omitted | age?: number |
| Children Prop | Nested content | children: ReactNode |
| Render Props | Function as child | render={(data) => ...} |
| Component Composition | Pass components | header={<Header />} |
Props Best Practices
- Keep props few – Aim for 3-5 props per component
- Use destructuring – Cleaner component code
- Provide default values – For optional props
- Type your props – TypeScript or PropTypes
- Avoid spreading unknown props – Can cause unexpected behavior
- Use meaningful names – Props should be self-documenting
- Don't mutate props – Props are read-only
- Use children for composition – More flexible than multiple props
Common Mistakes
Props vs State
| Aspect | Props | State |
|---|---|---|
| Mutability | Immutable (read-only) | Mutable (via setter) |
| Ownership | Parent component | Component itself |
| Purpose | Pass data/behavior | Track changes |
| Changes trigger re-render? | Yes (if parent changes) | Yes |
| Default values | Can have defaults | Initial values |
Conclusion
Props are essential for React component communication. They make components reusable and predictable. Use TypeScript or PropTypes for type safety, children for composition, and lift state up when needed. Avoid prop drilling by using Context or component composition.