Working with State and Props in React
What are Props?
-
Props (short for properties) are read-only inputs passed from a parent component to a child component.
-
They allow components to be dynamic and reusable by customizing their content or behavior.
-
Props are immutable inside the child component.
Example of Using Props
Here, name is a prop passed into Greeting to personalize the greeting.
What is State?
-
State is internal data managed within a component.
-
State can change over time, usually in response to user actions or events.
-
When state changes, React re-renders the component to update the UI.
-
Only class components or functional components with hooks manage state.
Using State in Functional Components with Hooks
React’s useState hook lets you add state to functional components.
-
countis the current state. -
setCountis a function to update the state. -
Calling
setCounttriggers a re-render with the new value.
Using State in Class Components
-
this.stateholds the internal state. -
Use
this.setState()to update it.
Props vs State Summary
| Feature | Props | State |
|---|---|---|
| Passed from | Parent component | Managed within the component |
| Mutable inside component? | No (read-only) | Yes (can change over time) |
| Purpose | To customize component | To manage internal dynamic data |
| Who controls? | Parent component | The component itself |
Passing State as Props
You can pass state values as props to child components for controlled data flow.
Summary
-
Props: inputs passed down, read-only, for customizing components.
-
State: internal, mutable data managed by components for dynamic behavior.
-
React re-renders components when state changes to update the UI.
