State vs Props in React: Clear Comparison
In React, State and Props are two core concepts that help manage data flow in components, but they serve different purposes. Here's a simple and clear comparison:
Feature | Props | State |
---|---|---|
Definition | Props (short for "properties") are used to pass data from parent to child components. | State is a local data storage that is controlled by the component itself. |
Mutability | Immutable – a component cannot change its props. | Mutable – a component can update its own state using setState (or useState in hooks). |
Usage | Used to configure a component, like arguments to a function. | Used to handle dynamic data that changes over time (like form inputs, toggles, etc.). |
Who Sets It? | The parent component sets the props for child components. | The component itself manages its own state internally. |
Access | Accessed via props object (this.props in class components or directly in function parameters in functional components). | Accessed via this.state (class components) or useState hook (functional components). |
Example | <UserCard name="John" age={30} /> — name and age are passed as props. | A counter app where count is a state variable updated when a button is clicked. |
Purpose | Communication between components. | Dynamic behavior and internal changes within a component. |
Quick Analogy:
- Props are like parameters you pass into a function.
- State is like variables declared inside a function that can change over time.
Example Code:
// Using Props function Welcome(props) { return <h1>Hello, {props.name}!</h1>; } // Using State import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
Final Thought:
- Props = Pass data into components.
- State = Manage data inside components.
Mastering both State and Props is essential to building powerful and dynamic React applications!