React & Modern Frontend (445 Qs)•Part 1: Core React, JSX & Component Architecture (1 - 77)
What is the difference between state and props?
In React, both state and props are plain JavaScript objects, but they serve different purposes and have distinct behaviors:
State
- Definition:
State is a data structure that is managed within a component. It represents information that can change over the lifetime of the component. - Mutability:
State is mutable, meaning it can be changed using the setter function (setStatein class components or the updater function fromuseStatein functional components). - Scope:
State is local to the component where it is defined. Only that component can modify its own state. - Usage:
State is typically used for data that needs to change in response to user actions, network responses, or other dynamic events. - Re-rendering:
Updating the state triggers a re-render of the component and its descendants.
Props
- Definition:
Props (short for “properties”) are inputs to a component, provided by its parent component. - Mutability:
Props are read-only. A component cannot modify its own props; they are immutable from the component’s perspective. - Scope:
Props are used to pass data and event handlers down the component tree, enabling parent components to configure or communicate with their children. - Usage:
Props are commonly used to make components reusable and configurable. They allow the same component to be rendered with different data or behavior. - Analogy:
Think of props as arguments to a function, whereas state is like variables declared inside the function.
Summary Table
| Feature | State | Props |
|---|---|---|
| Managed by | The component itself | Parent component |
| Mutable | Yes | No (read-only) |
| Scope | Local to the component | Passed from parent to child |
| Usage | Manage dynamic data and UI changes | Configure and customize component |
| Update | Using setState/useState | Cannot be updated by the component |
Practical Code Example
jsx
// Props: Passed from parent, READ-ONLY
function UserCard({ name, role }) {
// State: Managed internally within component, MUTABLE via setter
const [isOnline, setIsOnline] = useState(false);
return (
<div>
<h3>{name} ({role})</h3>
<button onClick={() => setIsOnline(!isOnline)}>
Status: {isOnline ? 'Active' : 'Offline'}
</button>
</div>
);
}