InterviewHubPRO
Section Overview
Q11

Question 11 of 445

Part 1: Core React, JSX & Component Architecture (1 - 77)

2%
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 (setState in class components or the updater function from useState in 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

FeatureStateProps
Managed byThe component itselfParent component
MutableYesNo (read-only)
ScopeLocal to the componentPassed from parent to child
UsageManage dynamic data and UI changesConfigure and customize component
UpdateUsing setState/useStateCannot 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>
  );
}