Props vs State in React: A Complete Guide with Real Examples ??
Ever wondered when to use props and when to use state in your React components? Let's break it down with real-world examples that you'll encounter in actual projects!
Understanding the Basics ??
Props: Think "Properties"
State: Think "Internal Memory"
Real-World Examples ??
1. E-commerce Product Card
function ProductCard({ product, onAddToCart }) { // Props
const [isInWishlist, setIsInWishlist] = useState(false); // State
return (
<div className="product-card">
<img src={product.image} alt={product.name} />
<h3>{product.name}</h3>
<p>${product.price}</p>
{/* Using props */}
<button onClick={() => onAddToCart(product.id)}>
Add to Cart
</button>
{/* Using state */}
<button
onClick={() => setIsInWishlist(!isInWishlist)}
className={isInWishlist ? 'active' : ''}
>
{isInWishlist ? '??' : '??'}
</button>
</div>
);
}
2. User Profile Form
function ProfileForm({ user, onUpdate }) { // Props
// State for form fields
const [formData, setFormData] = useState({
name: user.name,
email: user.email,
bio: user.bio
});
const [errors, setErrors] = useState({}); // State for validation
const handleSubmit = (e) => {
e.preventDefault();
// Validation
const newErrors = {};
if (!formData.name) newErrors.name = 'Name is required';
if (!formData.email) newErrors.email = 'Email is required';
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors);
return;
}
onUpdate(formData);
};
return (
<form onSubmit={handleSubmit}>
<input
value={formData.name}
onChange={e => setFormData({
...formData,
name: e.target.value
})}
/>
{errors.name && <span className="error">{errors.name}</span>}
{/* Similar fields for email and bio */}
</form>
);
}
3. Navigation Menu with Mobile Toggle
function Navigation({ links, currentUser }) { // Props
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); // State
return (
<nav>
<div className="desktop-menu">
{links.map(link => (
<a key={link.id} href={link.url}>{link.text}</a>
))}
{currentUser && <span>Welcome, {currentUser.name}</span>}
</div>
<button
className="mobile-toggle"
onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
>
{isMobileMenuOpen ? '?' : '?'}
</button>
{isMobileMenuOpen && (
<div className="mobile-menu">
{/* Same links as desktop */}
</div>
)}
</nav>
);
}
When to Use Props ??
Example: Theme Configuration
领英推荐
function Button({ theme, size, children }) { // Props for configuration
return (
<button className={`btn-${theme} btn-${size}`}>
{children}
</button>
);
}
When to Use State ??
Example: Form Input with Character Count
function TextArea({ maxLength }) { // Prop for configuration
const [text, setText] = useState(''); // State for user input
const [charCount, setCharCount] = useState(0); // Derived state
const handleChange = (e) => {
const newText = e.target.value;
if (newText.length <= maxLength) {
setText(newText);
setCharCount(newText.length);
}
};
return (
<div>
<textarea
value={text}
onChange={handleChange}
maxLength={maxLength}
/>
<span>{charCount}/{maxLength} characters</span>
</div>
);
}
Best Practices ??
?? Weekly Challenge
Create a Rating component that:
Share your solution in the comments!
#React #WebDevelopment #JavaScript #Programming #FrontEnd #ReactJS #LinkedInLearning
Follow me for more React tips and tutorials! Next week: The Component Lifecycle & useEffect Hook ??