What is the difference between state and props?

Prathap
2 min readMar 16, 2024

In React, both state and props are used to manage data within components, but they serve different purposes and have distinct characteristics.

Props (Properties):

  1. Immutability: Props are immutable, meaning they cannot be modified by the component that receives them. They are passed down from parent to child components and remain unchanged throughout the component’s lifecycle.
  2. Passed from Parent: Props are passed from parent components to child components. Parent components can pass data or functionality to their child components through props.
  3. Read-Only: Components can access props via this.props (in class components) or directly as an argument in functional components. However, components cannot modify props directly.
  4. Usage: Props are typically used for passing data from a parent component to its children, as well as for configuring or customizing child components.

Example:

function ParentComponent() {
const data = "Hello from Parent";
return <ChildComponent message={data} />;
}

function ChildComponent(props) {
return <div>{props.message}</div>;
}

State:

  1. Mutable: State is mutable and can be updated within the component using the setState() method. Changes to state trigger re-renders of the component and its children.
  2. Local to Component: State is local to the component in which it is defined. It is not accessible from outside the component, and each component instance maintains its own state.
  3. Initialization: State is typically initialized within the constructor of a class component using this.state = { /* initial state */ }, or using the useState hook in functional components.
  4. Usage: State is used to manage data that may change over time within a component, such as user input, UI state, or data fetched from APIs.

Example:

import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

Key Differences:

  1. Mutability: Props are immutable and passed from parent to child, while state is mutable and local to the component.
  2. Ownership: Props are owned by the parent component and passed down to children, while state is owned and managed by the component itself.
  3. Access: Props are accessed using this.props or as function arguments, while state is accessed using this.state in class components or via state hooks in functional components.
  4. Usage: Props are used for passing data and configuration to child components, while state is used for managing component-specific data and UI state changes.

In summary, while both state and props are used for managing data within React components, understanding their differences is crucial for effective component design and data management.

--

--