Props vs State in React: A Complete Guide with Real Examples ??

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"

  • Read-only data passed from parent components
  • Like function parameters
  • Can't be modified by the component

State: Think "Internal Memory"

  • Mutable data managed within the component
  • Like variables inside a function
  • Can be updated using setState/useState

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 ??

  1. When data comes from a parent component
  2. When data should be read-only
  3. When you need to share data across components
  4. For component configuration

Example: Theme Configuration

function Button({ theme, size, children }) {  // Props for configuration
  return (
    <button className={`btn-${theme} btn-${size}`}>
      {children}
    </button>
  );
}        

When to Use State ??

  1. When data changes over time
  2. For user interactions
  3. For form inputs
  4. For toggling UI elements

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 ??

  1. Props:

  • Keep them immutable
  • Use prop types or TypeScript
  • Pass only what's needed
  • Use meaningful names


  • 2. State:
  • Keep it minimal
  • Don't duplicate data
  • Lift state up when needed
  • Use derived state carefully


?? Weekly Challenge

Create a Rating component that:

  • Accepts a maxStars prop (default: 5)
  • Uses state to track the selected rating
  • Shows filled (?) and empty (☆) stars
  • Allows users to change rating by clicking
  • Includes a "Reset" button

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 ??

要查看或添加评论,请登录

Dhruv Patel的更多文章

社区洞察

其他会员也浏览了