0
0
Reactframework~5 mins

State vs props comparison in React

Choose your learning style9 modes available
Introduction

State and props help React components manage and share data. State is for data that changes inside a component. Props are for passing data from parent to child components.

When a component needs to remember user input or interaction.
When you want to send information from a parent component to a child component.
When a component's data changes over time and affects what it shows.
When you want to keep some data private inside a component.
When you want to reuse a component with different data.
Syntax
React
const [state, setState] = React.useState(initialValue);
<ComponentName propName={value} />

State is created inside a component using useState hook.

Props are passed to components like HTML attributes.

Examples
This creates a state variable count starting at 0.
React
const [count, setCount] = React.useState(0);
This passes a prop called name with value "Alice" to the Greeting component.
React
<Greeting name="Alice" />
This component uses the name prop to show a greeting.
React
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}
Sample Program

This example shows a Counter component with state count. The button changes the state. The Message child component receives the count as a prop and displays it.

React
import React, { useState } from 'react';

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

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increase</button>
      <Message count={count} />
    </div>
  );
}

function Message({ count }) {
  return <p>The current count is {count}.</p>;
}

export default Counter;
OutputSuccess
Important Notes

State is private and controlled inside the component.

Props are read-only and cannot be changed by the child component.

Changing state causes the component to update and show new data.

Summary

State holds data that can change inside a component.

Props pass data from parent to child components.

Use state for data that changes; use props to share data.