Skip to main content

State Management

In React, props and state are two essential concepts used for managing data and making components interactive. While both serve the purpose of storing data, they have distinct roles and behaviors.

Props (Properties)

Props are short for "properties" and are a way to pass data from a parent component to a child component. Props are read-only and immutable, meaning they cannot be changed by the child component receiving them. They allow data to flow downwards in a component hierarchy, enabling child components to receive and display data managed by their parent.

Key Points:

  • Immutable: Cannot be modified by the receiving component.
  • Data Flow: Passes data from a parent to a child component (one-way data flow).
  • Used For: Customizing child components, setting initial values, and configuring components with external data.

Example:

function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

function App() {
return <Greeting name="Alice" />;
}`

In this example, name is a prop passed from App to Greeting, which then displays "Hello, Alice!"

State

State is a built-in React object used to store data that can change over time. Unlike props, state is mutable, meaning it can be updated within the component. A component's state determines its behavior and appearance at any given time. When the state changes, React automatically re-renders the component to reflect the latest state.

Key Points:

  • Mutable: Can be changed by the component owning it.
  • Managed Internally: State is local to the component and cannot be accessed by other components directly.
  • Used For: Tracking user inputs, managing UI interactions, handling component-specific data that may change over time.

Example:

import React, { useState } from 'react';

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

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}`

In this example, count is a state variable, and setCount is used to update its value. Every time the button is clicked, count increments by 1, causing the component to re-render.

Differences Between Props and State

FeaturePropsState
MutabilityImmutable (read-only)Mutable (can be updated)
OwnershipPassed from parent to childLocal to the component
PurposeConfiguration, initial valuesDynamic data that changes
UpdateSet by parentManaged within the component

When to Use Props vs. State

  • Use props to pass data from a parent component to child components when the data does not need to be modified by the child.
  • Use state to handle data that changes over time within a component, such as user interactions or form inputs.

Both props and state are essential to creating dynamic, interactive React applications by allowing data flow and UI updates across different components.